Browse Source

Merge branch 'master' of https://code.ffdn.org/FFDN/coin into export-materiel

cecile 6 years ago
parent
commit
0a8c53a5ed
100 changed files with 2787 additions and 436 deletions
  1. 661 0
      LICENSE
  2. 45 3
      README.md
  3. 1 0
      coin/billing/__init__.py
  4. 64 3
      coin/billing/admin.py
  5. 9 0
      coin/billing/app.py
  6. 1 1
      coin/billing/create_subscriptions_invoices.py
  7. 17 0
      coin/billing/forms.py
  8. 297 0
      coin/billing/import_payments_from_csv.py
  9. 7 272
      coin/billing/management/commands/import_payments_from_csv.py
  10. 20 0
      coin/billing/migrations/0011_auto_20180819_0221.py
  11. 3 2
      coin/billing/models.py
  12. 5 0
      coin/billing/templates/admin/billing/payment/change_list.html
  13. 54 0
      coin/billing/templates/admin/billing/payment/wizard_import_payment_csv.html
  14. 2 0
      coin/billing/templates/billing/invoice.html
  15. 3 0
      coin/billing/templates/billing/invoice_pdf.html
  16. 0 2
      coin/billing/urls.py
  17. 2 9
      coin/billing/views.py
  18. 2 0
      coin/configuration/forms.py
  19. 1 0
      coin/isp_database/__init__.py
  20. 9 0
      coin/isp_database/app.py
  21. 8 1
      coin/isp_database/context_processors.py
  22. 1 0
      coin/members/__init__.py
  23. 114 17
      coin/members/admin.py
  24. 8 0
      coin/members/app.py
  25. 41 1
      coin/members/forms.py
  26. 4 5
      coin/members/management/commands/call_for_membership_fees.py
  27. 0 42
      coin/members/membershipfee_filter.py
  28. 1 1
      coin/members/migrations/0003_auto_20141007_0956.py
  29. 1 1
      coin/members/migrations/0004_auto_20141007_1002.py
  30. 23 0
      coin/members/migrations/0018_auto_20180819_0211.py
  31. 71 8
      coin/members/models.py
  32. 21 0
      coin/members/registration_views.py
  33. 4 1
      coin/members/templates/admin/members/member/change_form.html
  34. 39 0
      coin/members/templates/admin/members/member/delete_confirmation.html
  35. 1 0
      coin/members/templates/members/contact.html
  36. 2 0
      coin/members/templates/members/detail.html
  37. 9 0
      coin/members/templates/members/emails/new_member_email.html
  38. 1 0
      coin/members/templates/members/emails/new_member_email_subject.txt
  39. 2 0
      coin/members/templates/members/index.html
  40. 3 1
      coin/members/templates/members/invoices.html
  41. 10 0
      coin/members/templates/members/registration/activate.html
  42. 20 0
      coin/members/templates/members/registration/activation_complete.html
  43. 12 0
      coin/members/templates/members/registration/activation_email.txt
  44. 1 0
      coin/members/templates/members/registration/activation_email_subject.txt
  45. 13 4
      coin/members/templates/members/registration/login.html
  46. 3 0
      coin/members/templates/members/registration/password_change_base.html
  47. 1 3
      coin/members/templates/members/registration/password_change_done.html
  48. 3 2
      coin/members/templates/members/registration/password_change_form.html
  49. 3 0
      coin/members/templates/members/registration/password_reset_base.html
  50. 1 1
      coin/members/templates/members/registration/password_reset_complete.html
  51. 1 1
      coin/members/templates/members/registration/password_reset_confirm.html
  52. 2 1
      coin/members/templates/members/registration/password_reset_done.html
  53. 1 1
      coin/members/templates/members/registration/password_reset_form.html
  54. 3 0
      coin/members/templates/members/registration/registration_base.html
  55. 6 0
      coin/members/templates/members/registration/registration_closed.html
  56. 6 0
      coin/members/templates/members/registration/registration_complete.html
  57. 66 0
      coin/members/templates/members/registration/registration_form.html
  58. 2 0
      coin/members/templates/members/subscriptions.html
  59. 69 5
      coin/members/tests.py
  60. 44 3
      coin/members/urls.py
  61. 24 17
      coin/members/views.py
  62. 2 0
      coin/mixins.py
  63. 1 0
      coin/offers/__init__.py
  64. 9 0
      coin/offers/app.py
  65. 11 0
      coin/offers/fixtures/offers.json
  66. 67 1
      coin/settings_base.py
  67. 1 0
      coin/settings_test.py
  68. 18 0
      coin/static/css/admin-local.css
  69. 53 13
      coin/static/css/local.css
  70. 6 1
      coin/templates/admin/base_site.html
  71. 15 2
      coin/templates/base.html
  72. 5 0
      coin/templates/menu_items.html
  73. 8 0
      coin/urls.py
  74. 3 0
      coin/utils.py
  75. 3 4
      coin/views.py
  76. 1 1
      contrib/ansible/coin-customizations/django_local_settings.py.j2
  77. BIN
      doc/_img/admin-maillists.png
  78. BIN
      doc/_img/user-maillists.png
  79. BIN
      doc/_img/user-subscriptions.png
  80. 125 0
      doc/admin/maillists.md
  81. 25 0
      hardware_provisioning/migrations/0018_auto_20180819_0211.py
  82. 3 2
      hardware_provisioning/models.py
  83. 3 1
      hardware_provisioning/templates/hardware_provisioning/item_borrow.html
  84. 2 1
      hardware_provisioning/templates/hardware_provisioning/item_list.html
  85. 2 0
      hardware_provisioning/templates/hardware_provisioning/list.html
  86. 3 1
      hardware_provisioning/templates/hardware_provisioning/return.html
  87. 3 1
      hardware_provisioning/templates/hardware_provisioning/transfer.html
  88. 1 0
      housing/__init__.py
  89. 84 0
      housing/admin.py
  90. 14 0
      housing/apps.py
  91. 30 0
      housing/migrations/0001_initial.py
  92. 0 0
      housing/migrations/__init__.py
  93. 111 0
      housing/models.py
  94. 40 0
      housing/templates/housing/housing.html
  95. 124 0
      housing/tests.py
  96. 13 0
      housing/urls.py
  97. 34 0
      housing/views.py
  98. 1 0
      maillists/__init__.py
  99. 118 0
      maillists/admin.py
  100. 0 0
      maillists/app.py

+ 661 - 0
LICENSE

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

+ 45 - 3
README.md

@@ -4,6 +4,9 @@ The COIN project
 `Coin` is Illyse's Information System, designed to manage both members
 and Internet accesses, such as through DSL, VPN, wireless…
 
+
+![example of a coin user view : the subscriptions list](doc/_img/user-subscriptions.png)
+
 It is written in Django, and features a generic configuration interface,
 which allows to implement custom backends for different technologies.
 Currently implemented is a LDAP-based backend for OpenVPN, and a very
@@ -19,6 +22,11 @@ The project page (issue, wiki, etc) is here:
 
 A mailing list is available, for both users and developers: https://listes.illyse.org/wws/info/si
 
+License
+=======
+
+Coin is released under the GNU Affero GPL 3.0 license.  See `LICENSE` for details.
+
 Extending Coin
 ==============
 
@@ -50,7 +58,7 @@ Install dependencies. On Debian, you will probably need the
 `python-dev`, `python-pip`, `libldap-dev`, `libpq-dev`, `libsasl2-dev`,
 and `libjpeg-dev` packages.
 
-    sudo apt-get install python-dev python-pip libldap2-dev libpq-dev libsasl2-dev libjpeg-dev libxml2-dev libxslt1-dev libffi-dev
+    sudo apt-get install python-dev python-pip libldap2-dev libpq-dev libsasl2-dev libjpeg-dev libxml2-dev libxslt1-dev libffi-dev python-cairo libpango1.0-0
 
 You need a recent *pip* for the installation of dependencies to work. If you
 don't meet that requirement (Ubuntu trusty does not), run:
@@ -315,6 +323,10 @@ Some apps are not enabled by default :
    any authentication backend or user configuration ("marque blanche")
 - *hardware_provisioning* : Self-service app to manage hardware inventory,
   hardware lent to members or in different stock sites.
+- *maillists* : Self-service mailling-list (un)subscription for members:
+  handles subscribers list for a third-party mailling-list server (sympa,
+  mailman…
+  etc). See [maillists app documentation (fr)](doc/admin/maillists.md).
 
 You can enable them using the `EXTRA_INSTALLED_APPS` setting.
 E.g. in `settings_local.py`:
@@ -335,15 +347,45 @@ Settings
 
 List of available settings in your `settings_local.py` file.
 
-- `EXTRA_INSTALLED_APPS`: See *Customizing app list*
-- `EXTRA_TEMPLATE_DIRS`: See *Customizing templates*
+- `EXTRA_INSTALLED_APPS`: See [using optional apps](#using-optional-apps)
+- `EXTRA_TEMPLATE_DIRS`: See [customizing templates](#customizing-templates)
 - `LDAP_ACTIVATE`: See *LDAP*
 - `MEMBER_MEMBERSHIP_INFO_URL`: Link to a page with information on how to become a member or pay the membership fee
+- `MEMBERSHIP_FEE_REMINDER_DATES`: how long before/after the membership fee
+  anniversary date we want to send a reminder email to the member. It defaults
+  to the following:
+
+```
+MEMBERSHIP_FEE_REMINDER_DATES = [
+    {'months': -3},  # 3 months before
+    {'months': -2},  # 2 months before
+    {'months': -1},  # 1 month before
+    {'days': 0},     # the day of anniversary
+    {'months': +1},  # 1 month after
+]
+```
 - `SUBSCRIPTION_REFERENCE`: Pattern used to display a unique reference for any subscription. Helpful for bank wire transfer identification
+- `REGISTRATION_OPEN` : Allow visitor to join the association by register on COIN
+- `ACCOUNT_ACTIVATION_DAYS` : All account with unvalidated email will be deleted after X days
+- `MEMBERSHIP_REFERENCE` : Template string to display the label the member should indicates for the bank transfer, default: "ADH-{{ user.pk }}"
+- `DEFAULT_MEMBERSHIP_FEE` : Default membership fee, if you have a more complex membership fees policy, you could overwrite templates
 - `PAYMENT_DELAY`: Payment delay in days for issued invoices ( default is 30 days which is the default in french law)
 - `MEMBER_CAN_EDIT_PROFILE`: Allow members to edit their profiles
 - `HANDLE_BALANCE`: Allows to handle money balances for members (False default)
 - `INVOICES_INCLUDE_CONFIG_COMMENTS`: Add comment related to a subscription configuration when generating invoices
+- `MEMBER_CAN_EDIT_VPN_CONF`: Allow members to edit some part of their vpn configuration
+- `MAILLIST_SYNC_COMMAND` : The command to send the list of mail addresses of a
+  given mailling list to mail list server. The command will receives one
+  address/line on stdin. This setting could use placholders:
+    - `{email}`: the mail address of the list
+    - `{short_name}`: the list name
+- `DEBUG` : Enable debug for development **do not use in production** : display
+   stracktraces and enable [django-debug-toolbar](https://django-debug-toolbar.readthedocs.io).
+- `SITE_TITLE`: the base of site title (displayed in browser window/tab title)
+- `SITE_HEADER`: the site header (displayed in all pages as page header)
+- `SITE_LOGO_URL`: URL to website logo (by default, this is an ascii-duck)
+- `SUBSCRIPTIONS_NOTIFICATION_EMAILS` : Emails on which to send notifications
+  uppon new registration.
 
 Accounting logs
 ---------------

+ 1 - 0
coin/billing/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'coin.billing.app.BillingConfig'

+ 64 - 3
coin/billing/admin.py

@@ -7,6 +7,7 @@ from django.http import HttpResponseRedirect
 from django.conf.urls import url
 from django.contrib.admin.utils import flatten_fieldsets
 from django import forms
+from django.shortcuts import render
 
 from coin.filtering_queryset import LimitedAdminInlineMixin
 from coin.billing.models import Invoice, InvoiceDetail, Payment, PaymentAllocation
@@ -14,6 +15,8 @@ from coin.billing.utils import get_invoice_from_id_or_number
 from django.core.urlresolvers import reverse
 import autocomplete_light
 
+from .forms import WizardImportPaymentCSV
+from .import_payments_from_csv import process, add_new_payments
 
 class InvoiceDetailInlineForm(forms.ModelForm):
     class Meta:
@@ -103,10 +106,17 @@ class PaymentInlineAdd(admin.StackedInline):
         return False
 
 
+class DummyPaymentInlineAdd(PaymentInlineAdd):
+    def has_add_permission(self, request):
+        return False
+
+
 class InvoiceAdmin(admin.ModelAdmin):
+    list_display_links = ('number', 'date')
+    list_filter = ('status', 'validated', 'date')
+    search_fields = ['member__username', 'member__first_name', 'member__last_name', 'member__email', 'member__nickname', 'number']
     list_display = ('number', 'date', 'status', 'amount', 'member',
                     'validated')
-    list_display_links = ('number', 'date')
     fields = (('number', 'date', 'status'),
               ('date_due'),
               ('member'),
@@ -121,12 +131,17 @@ class InvoiceAdmin(admin.ModelAdmin):
         """
         if obj and obj.validated:
             if self.declared_fieldsets:
-                return flatten_fieldsets(self.declared_fieldsets)
+                ro_fields = flatten_fieldsets(self.declared_fieldsets)
             else:
-                return list(set(
+                ro_fields = list(set(
                     [field.name for field in self.opts.local_fields] +
                     [field.name for field in self.opts.local_many_to_many]
                 ))
+            try:
+                ro_fields.remove("status")
+            except:
+                pass
+            return ro_fields
         return self.readonly_fields
 
     def get_inline_instances(self, request, obj=None):
@@ -149,6 +164,11 @@ class InvoiceAdmin(admin.ModelAdmin):
                 inlines += [PaymentAllocatedReadOnly]
                 if obj.status == "open":
                     inlines += [PaymentInlineAdd]
+                else:
+                    # if we do not provide any inline, coin will yell on
+                    # closed->open status, expecting POST data with Payment
+                    # inline data. Thus, we provide an empty.
+                    inlines += [DummyPaymentInlineAdd]
 
         for inline_class in inlines:
             inline = inline_class(self.model, self.admin_site)
@@ -238,5 +258,46 @@ class PaymentAdmin(admin.ModelAdmin):
     def get_inline_instances(self, request, obj=None):
         return [PaymentAllocationInlineReadOnly(self.model, self.admin_site)]
 
+    def get_urls(self):
+
+        urls = super(PaymentAdmin, self).get_urls()
+
+        my_urls = [
+            url(r'wizard_import_payment_csv/$', self.wizard_import_payment_csv, name='wizard_import_payment_csv'),
+        ]
+
+        return my_urls + urls
+
+
+    def wizard_import_payment_csv(self, request):
+        template = "admin/billing/payment/wizard_import_payment_csv.html"
+
+        if request.method == 'POST':
+            form = WizardImportPaymentCSV(request.POST, request.FILES)
+            if form.is_valid():
+
+                # Analyze
+                new_payments = process(request.FILES["csv_file"])
+
+                # If the user didn't ask for commit yet
+                # display the result of the analyze (i.e. the matching)
+                if "commit" not in request.POST:
+                    return render(request, template, {
+                        'adminform': form,
+                        'opts': self.model._meta,
+                        'new_payments': new_payments
+                        })
+                else:
+                    add_new_payments(new_payments)
+                    return HttpResponseRedirect('../')
+        else:
+            form = WizardImportPaymentCSV()
+
+        return render(request, template, {
+            'adminform': form,
+            'opts': self.model._meta
+            })
+
+
 admin.site.register(Invoice, InvoiceAdmin)
 admin.site.register(Payment, PaymentAdmin)

+ 9 - 0
coin/billing/app.py

@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+from django.apps import AppConfig
+
+
+class BillingConfig(AppConfig):
+    name = 'coin.billing'
+    verbose_name = 'Facturation'

+ 1 - 1
coin/billing/create_subscriptions_invoices.py

@@ -47,7 +47,7 @@ def create_member_invoice_for_a_period(member, date):
                           relativedelta(days=+1))
 
     invoice = Invoice.objects.create(
-        date_due=datetime.date.today(),
+        date_due=datetime.date.today() + datetime.timedelta(days=settings.PAYMENT_DELAY),
         member=member
     )
 

+ 17 - 0
coin/billing/forms.py

@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import os
+
+from django.core.exceptions import ValidationError
+from django import forms
+
+def validate_file_extension(value):
+    ext = os.path.splitext(value.name)[1]
+    valid_extensions = ['.csv']
+    if not ext.lower() in valid_extensions:
+        raise ValidationError(u'Unsupported file extension.')
+
+class WizardImportPaymentCSV(forms.Form):
+
+    csv_file = forms.FileField(validators=[validate_file_extension])

+ 297 - 0
coin/billing/import_payments_from_csv.py

@@ -0,0 +1,297 @@
+# -*- coding: utf-8 -*-
+"""
+Import payments from a CSV file from a bank.  The payments will automatically be
+parsed, and there'll be an attempt to automatically match payments with members.
+
+The matching is performed using the label of the payment.
+- First, try to find a string such as 'ID-42' where 42 is the member's ID
+- Second (if no ID found), try to find a member username (with no ambiguity with
+  respect to other usernames)
+- Third (if no username found), try to find a member family name (with no
+  ambiguity with respect to other family name)
+
+This script will check if a payment has already been registered with same
+properies (date, label, price) to avoid creating duplicate payments inside coin.
+
+By default, only a dry-run is perfomed to let you see what will happen ! You
+should run this command with --commit if you agree with the dry-run.
+"""
+
+from __future__ import unicode_literals
+
+# Standard python libs
+import csv
+import datetime
+import logging
+import re
+
+import unidecode
+
+# Coin specific imports
+from coin.members.models import Member
+from coin.billing.models import Payment
+
+# Parser / import / matcher configuration
+
+# The CSV delimiter
+DELIMITER = str(';')
+# The date format in the CSV
+DATE_FORMAT = "%d/%m/%Y"
+# The default regex used to match the label of a payment with a member ID
+ID_REGEX = r"(?i)(\b|_)ID[\s\-\_\/]*(\d+)(\b|_)"
+# If the label of the payment contains one of these, the payment won't be
+# matched to a member when importing it.
+KEYWORDS_TO_NOTMATCH = ["REM CHQ"]
+
+################################################################################
+
+
+def process(f):
+
+    raw_csv = list(csv.reader(f, delimiter=DELIMITER))
+    cleaned_csv = clean_csv(raw_csv)
+
+    payments = convert_csv_to_dicts(cleaned_csv)
+
+    payments = try_to_match_payment_with_members(payments)
+    new_payments = filter_already_known_payments(payments)
+    new_payments = unmatch_payment_with_keywords(new_payments)
+
+    return new_payments
+
+
+def is_date(text):
+    try:
+        datetime.datetime.strptime(text, DATE_FORMAT)
+        return True
+    except ValueError:
+        return False
+
+
+def is_money_amount(text):
+    try:
+        float(text.replace(",","."))
+        return True
+    except ValueError:
+        return False
+
+
+def load_csv(filename):
+    with open(filename, "r") as f:
+        return list(csv.reader(f, delimiter=DELIMITER))
+
+
+def clean_csv(data):
+
+    output = []
+
+    for i, row in enumerate(data):
+
+        if len(row) < 4:
+            continue
+
+        if not is_date(row[0]):
+            logging.warning("Ignoring the following row (bad format for date in the first column) :")
+            logging.warning(str(row))
+            continue
+
+        if is_money_amount(row[2]):
+            logging.warning("Ignoring row %s (not a payment)" % str(i))
+            logging.warning(str(row))
+            continue
+
+        if not is_money_amount(row[3]):
+            logging.warning("Ignoring the following row (bad format for money amount in colun three) :")
+            logging.warning(str(row))
+            continue
+
+        # Clean the date
+        row[0] = datetime.datetime.strptime(row[0], DATE_FORMAT).strftime("%Y-%m-%d")
+
+        # Clean the label ...
+        row[4] = row[4].replace('\r', ' ')
+        row[4] = row[4].replace('\n', ' ')
+
+        output.append(row)
+
+    return output
+
+
+def convert_csv_to_dicts(data):
+
+    output = []
+
+    for row in data:
+        payment = {}
+
+        payment["date"] = row[0]
+        payment["label"] = row[4]
+        payment["amount"] = float(row[3].replace(",","."))
+
+        output.append(payment)
+
+    return output
+
+
+def try_to_match_payment_with_members(payments):
+
+    members = Member.objects.all()
+
+    idregex = re.compile(ID_REGEX)
+
+    for payment in payments:
+
+        payment_label = payment["label"].upper()
+
+        # First, attempt to match the member ID
+        idmatches = idregex.findall(payment_label)
+        if len(idmatches) == 1:
+            i = int(idmatches[0][1])
+            member_matches = [ member.username for member in members if member.pk==i ]
+            if len(member_matches) == 1:
+                payment["member_matched"] = member_matches[0]
+                #print("Matched by ID to "+member_matches[0])
+                continue
+
+
+        # Second, attempt to find the username
+        usernamematch = None
+        for member in members:
+            username = flatten(member.username)
+            matches = re.compile(r"(?i)(\b|_)"+re.escape(username)+r"(\b|_)") \
+                        .findall(payment_label)
+
+            # If not found, try next
+            if len(matches) == 0:
+                continue
+
+            # If we already had a match, abort the whole search because we
+            # have multiple usernames matched !
+            if usernamematch != None:
+                usernamematch = None
+                break
+
+            usernamematch = member.username
+
+        if usernamematch != None:
+            payment["member_matched"] = usernamematch
+            #print("Matched by username to "+usernamematch)
+            continue
+
+
+        # Third, attempt to match by family name
+        familynamematch = None
+        for member in members:
+            if member.last_name == "":
+                continue
+
+            # "Flatten" accents in the last name... (probably the CSV
+            # don't contain 'special' chars like accents
+            member_last_name = flatten(member.last_name)
+
+            matches = re.compile(r"(?i)(\b|_)"+re.escape(member_last_name)+r"(\b|_)") \
+                        .findall(payment_label)
+
+            # If not found, try next
+            if len(matches) == 0:
+                continue
+
+            # If this familyname was matched several time, abort the whole search
+            #if len(matches) > 1:
+            #    print("Several matches ! Aborting !")
+            #    familynamematch = None
+            #    break
+
+            # If we already had a match, abort the whole search because we
+            # have multiple familynames matched !
+            if familynamematch != None:
+                familynamematch = None
+                break
+
+            familynamematch = member_last_name
+            usernamematch = member.username
+
+        if familynamematch != None:
+            payment["member_matched"] = usernamematch
+            #print("Matched by familyname to "+familynamematch)
+            continue
+
+        #print("Could not match")
+        payment["member_matched"] = None
+
+    return payments
+
+
+def unmatch_payment_with_keywords(payments):
+
+    matchers = {}
+    for keyword in KEYWORDS_TO_NOTMATCH:
+        matchers[keyword] = re.compile(r"(?i)(\b|_|-)"+re.escape(keyword)+r"(\b|_|-)")
+
+    for i, payment in enumerate(payments):
+
+        # If no match found, don't filter anyway
+        if payment["member_matched"] == None:
+            continue
+
+        for keyword, matcher in matchers.items():
+            matches = matcher.findall(payment["label"])
+
+            # If not found, try next
+            if len(matches) == 0:
+                continue
+
+            #print("Ignoring possible match for payment '%s' because " \
+            #      "it contains the keyword %s"                        \
+            #      % (payment["label"], keyword))
+            payments[i]["member_matched"] = None
+
+            break
+
+    return payments
+
+def filter_already_known_payments(payments):
+
+    new_payments = []
+
+    known_payments = Payment.objects.all()
+
+    for payment in payments:
+
+        found_match = False
+        for known_payment in known_payments:
+
+            if  (str(known_payment.date) == payment["date"].encode('utf-8')) \
+            and (known_payment.label == payment["label"]) \
+            and (float(known_payment.amount) == float(payment["amount"])):
+                found_match = True
+                break
+
+        if not found_match:
+            new_payments.append(payment)
+
+    return new_payments
+
+
+def add_new_payments(new_payments):
+
+    for new_payment in new_payments:
+
+        # Get the member if there's a member matched
+        member = None
+        if new_payment["member_matched"]:
+            member = Member.objects.filter(username=new_payment["member_matched"])
+            assert len(member) == 1
+            member = member[0]
+
+        print("Adding new payment : ")
+        print(new_payment)
+
+        # Create the payment
+        payment = Payment.objects.create(amount=float(new_payment["amount"]),
+                                         label=new_payment["label"],
+                                         date=new_payment["date"],
+                                         member=member)
+
+def flatten(some_string):
+    return unidecode.unidecode(some_string).upper()

+ 7 - 272
coin/billing/management/commands/import_payments_from_csv.py

@@ -20,34 +20,18 @@ should run this command with --commit if you agree with the dry-run.
 from __future__ import unicode_literals
 
 # Standard python libs
-import csv
-import datetime
 import json
-import logging
 import os
-import re
-
-import unidecode
 
 # Django specific imports
 from argparse import RawTextHelpFormatter
 from django.core.management.base import BaseCommand, CommandError
 
 # Coin specific imports
-from coin.members.models import Member
-from coin.billing.models import Payment
+from coin.billing.import_payments_from_csv import process, add_new_payments
 
-# Parser / import / matcher configuration
+################################################################################
 
-# The CSV delimiter
-DELIMITER=str(';')
-# The date format in the CSV
-DATE_FORMAT="%d/%m/%Y"
-# The default regex used to match the label of a payment with a member ID
-ID_REGEX=r"(?i)(\b|_)ID[\s\-\_\/]*(\d+)(\b|_)"
-# If the label of the payment contains one of these, the payment won't be
-# matched to a member when importing it.
-KEYWORDS_TO_NOTMATCH=[ "REM CHQ" ]
 
 class Command(BaseCommand):
 
@@ -74,30 +58,22 @@ class Command(BaseCommand):
             help='Agree with the proposed change and commit them'
         )
 
-
     def handle(self, *args, **options):
 
         assert options["filename"] != ""
         if not os.path.isfile(options["filename"]):
             raise CommandError("This file does not exists.")
-        os.system("iconv -f ISO-8859-1 -t UTF-8 %s > %s.utf8.csv" % (options["filename"], options["filename"]))
-        options["filename"] = options["filename"] + '.utf8.csv'
-
-        payments = self.convert_csv_to_dicts(self.clean_csv(self.load_csv(options["filename"])))
 
-        payments = self.try_to_match_payment_with_members(payments)
-        new_payments = self.filter_already_known_payments(payments)
-        new_payments = self.unmatch_payment_with_keywords(new_payments)
+        f = open(options["filename"], "r")
+        new_payments = process(f)
 
-        number_of_already_known_payments = len(payments)-len(new_payments)
         number_of_new_payments = len(new_payments)
 
-        if (number_of_new_payments > 0) :
+        if (number_of_new_payments > 0):
             print("======================================================")
             print("   > New payments found")
             print(json.dumps(new_payments, indent=4, separators=(',', ': ')))
         print("======================================================")
-        print("Number of already known payments found : " + str(number_of_already_known_payments))
         print("Number of new payments found           : " + str(number_of_new_payments))
         print("Number of new payments matched         : " + str(len([p for p in new_payments if     p["member_matched"]])))
         print("Number of payments not matched         : " + str(len([p for p in new_payments if not p["member_matched"]])))
@@ -108,248 +84,7 @@ class Command(BaseCommand):
             return
 
         if not options["commit"]:
-            print("Please carefully review the matches, then if everything \n" \
+            print("Please carefully review the matches, then if everything \n"
                   "looks alright, use --commit to register these new payments.")
         else:
-            self.add_new_payments(new_payments)
-
-
-    def is_date(self, text):
-        try:
-            datetime.datetime.strptime(text, DATE_FORMAT)
-            return True
-        except ValueError:
-            return False
-
-
-    def is_money_amount(self, text):
-        try:
-            float(text.replace(",","."))
-            return True
-        except ValueError:
-            return False
-
-
-    def load_csv(self, filename):
-        with open(filename, "r") as f:
-            return list(csv.reader(f, delimiter=DELIMITER))
-
-
-    def clean_csv(self, data):
-
-        output = []
-
-        for i, row in enumerate(data):
-
-            for j in range(len(row)):
-                row[j] = row[j].decode('utf-8')
-
-            if len(row) < 4:
-                continue
-
-            if not self.is_date(row[0]):
-                logging.warning("Ignoring the following row (bad format for date in the first column) :")
-                logging.warning(str(row))
-                continue
-
-            if self.is_money_amount(row[2]):
-                logging.warning("Ignoring row %s (not a payment)" % str(i))
-                logging.warning(str(row))
-                continue
-
-            if not self.is_money_amount(row[3]):
-                logging.warning("Ignoring the following row (bad format for money amount in colun three) :")
-                logging.warning(str(row))
-                continue
-
-            # Clean the date
-            row[0] = datetime.datetime.strptime(row[0], DATE_FORMAT).strftime("%Y-%m-%d")
-
-            # Clean the label ...
-            row[4] = row[4].replace('\r', ' ')
-            row[4] = row[4].replace('\n', ' ')
-
-            output.append(row)
-
-        return output
-
-
-    def convert_csv_to_dicts(self, data):
-
-        output = []
-
-        for row in data:
-            payment = {}
-
-            payment["date"] = row[0]
-            payment["label"] = row[4]
-            payment["amount"] = float(row[3].replace(",","."))
-
-            output.append(payment)
-
-        return output
-
-
-    def try_to_match_payment_with_members(self, payments):
-
-        #members = Member.objects.filter(status="member")
-        members = Member.objects.all()
-
-        idregex = re.compile(ID_REGEX)
-
-        for payment in payments:
-
-            payment_label = payment["label"].upper()
-
-            # First, attempt to match the member ID
-            idmatches = idregex.findall(payment_label)
-            if len(idmatches) == 1:
-                i = int(idmatches[0][1])
-                member_matches = [ member.username for member in members if member.pk==i ]
-                if len(member_matches) == 1:
-                    payment["member_matched"] = member_matches[0]
-                    #print("Matched by ID to "+member_matches[0])
-                    continue
-
-
-            # Second, attempt to find the username
-            usernamematch = None
-            for member in members:
-                username = self.flatten(member.username)
-                matches = re.compile(r"(?i)(\b|_)"+re.escape(username)+r"(\b|_)") \
-                            .findall(payment_label)
-
-                # If not found, try next
-                if len(matches) == 0:
-                    continue
-
-                # If we already had a match, abort the whole search because we
-                # have multiple usernames matched !
-                if usernamematch != None:
-                    usernamematch = None
-                    break
-
-                usernamematch = member.username
-
-            if usernamematch != None:
-                payment["member_matched"] = usernamematch
-                #print("Matched by username to "+usernamematch)
-                continue
-
-
-            # Third, attempt to match by family name
-            familynamematch = None
-            for member in members:
-                if member.last_name == "":
-                    continue
-
-                # "Flatten" accents in the last name... (probably the CSV
-                # don't contain 'special' chars like accents
-                member_last_name = self.flatten(member.last_name)
-
-                matches = re.compile(r"(?i)(\b|_)"+re.escape(member_last_name)+r"(\b|_)") \
-                            .findall(payment_label)
-
-                # If not found, try next
-                if len(matches) == 0:
-                    continue
-
-                # If this familyname was matched several time, abort the whole search
-                #if len(matches) > 1:
-                #    print("Several matches ! Aborting !")
-                #    familynamematch = None
-                #    break
-
-                # If we already had a match, abort the whole search because we
-                # have multiple familynames matched !
-                if familynamematch != None:
-                    familynamematch = None
-                    break
-
-                familynamematch = member_last_name
-                usernamematch = member.username
-
-            if familynamematch != None:
-                payment["member_matched"] = usernamematch
-                #print("Matched by familyname to "+familynamematch)
-                continue
-
-            #print("Could not match")
-            payment["member_matched"] = None
-
-        return payments
-
-
-    def unmatch_payment_with_keywords(self, payments):
-
-        matchers = {}
-        for keyword in KEYWORDS_TO_NOTMATCH:
-            matchers[keyword] = re.compile(r"(?i)(\b|_|-)"+re.escape(keyword)+r"(\b|_|-)")
-
-        for i, payment in enumerate(payments):
-
-            # If no match found, don't filter anyway
-            if payment["member_matched"] == None:
-                continue
-
-            for keyword, matcher in matchers.items():
-                matches = matcher.findall(payment["label"])
-
-                # If not found, try next
-                if len(matches) == 0:
-                    continue
-
-                print("Ignoring possible match for payment '%s' because " \
-                      "it contains the keyword %s"                        \
-                      % (payment["label"], keyword))
-                payments[i]["member_matched"] = None
-
-                break
-
-        return payments
-
-    def filter_already_known_payments(self, payments):
-
-        new_payments = []
-
-        known_payments = Payment.objects.all()
-
-        for payment in payments:
-
-            found_match = False
-            for known_payment in known_payments:
-
-                if  (str(known_payment.date) == payment["date"].encode('utf-8')) \
-                and (known_payment.label == payment["label"]) \
-                and (float(known_payment.amount) == float(payment["amount"])):
-                    found_match = True
-                    break
-
-            if not found_match:
-                new_payments.append(payment)
-
-        return new_payments
-
-
-    def add_new_payments(self, new_payments):
-
-        for new_payment in new_payments:
-
-            # Get the member if there's a member matched
-            member = None
-            if new_payment["member_matched"]:
-                member = Member.objects.filter(username=new_payment["member_matched"])
-                assert len(member) == 1
-                member = member[0]
-
-            print("Adding new payment : ")
-            print(new_payment)
-
-            # Create the payment
-            payment = Payment.objects.create(amount=float(new_payment["amount"]),
-                                             label=new_payment["label"],
-                                             date=new_payment["date"],
-                                             member=member)
-
-    def flatten(self, some_string):
-        return unidecode.unidecode(some_string).upper()
+            add_new_payments(new_payments)

+ 20 - 0
coin/billing/migrations/0011_auto_20180819_0221.py

@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('billing', '0010_new_billing_system_data'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='invoicedetail',
+            name='offersubscription',
+            field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to='offers.OfferSubscription', null=True, verbose_name='abonnement'),
+        ),
+    ]

+ 3 - 2
coin/billing/models.py

@@ -326,6 +326,7 @@ class InvoiceDetail(models.Model):
                                 related_name='details')
     offersubscription = models.ForeignKey(OfferSubscription, null=True,
                                           blank=True, default=None,
+                                          on_delete=models.SET_NULL,
                                           verbose_name='abonnement')
     period_from = models.DateField(
         default=start_of_month,
@@ -440,10 +441,10 @@ class Payment(models.Model):
 
     def __unicode__(self):
         if self.member is not None:
-            return 'Paiment de {:0.2f}€ le {} par {}'.format(
+            return 'Paiment de {:0.2f}€ le {:%d/%m/%Y} par {}'.format(
                 self.amount, self.date, self.member)
         else:
-            return 'Paiment de {:0.2f}€ le {}'.format(
+            return 'Paiment de {:0.2f}€ le {:%d/%m/%Y}'.format(
                 self.amount, self.date)
 
     class Meta:

+ 5 - 0
coin/billing/templates/admin/billing/payment/change_list.html

@@ -0,0 +1,5 @@
+{% extends "admin/change_list.html" %}
+{% block object-tools-items %}
+    <li><a href="./wizard_import_payment_csv">Importer des paiements</a></li>
+{% endblock %}
+ 

+ 54 - 0
coin/billing/templates/admin/billing/payment/wizard_import_payment_csv.html

@@ -0,0 +1,54 @@
+{% extends "admin/change_form.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}
+<div class="breadcrumbs">
+    <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
+    &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
+    &rsaquo; <a href="">Importer des paiements depuis un CSV</a>
+</div>
+{% endblock %}
+
+{% block content %}
+<h1>Importer des paiements depuis un CSV</h1>
+<div id="content-main">
+    <form method="POST" action="."  enctype="multipart/form-data">
+        {% csrf_token %}
+        <fieldset style="text-align:center;">
+            {{ adminform.as_p }}
+            {% if not new_payments %}
+                <input type="submit" value="Analser (simulation)" class="default" style="float: none; margin: 0 auto;"/>
+            {% else %}
+                <input type="checkbox" id="commit" name="commit" value="1" style="display:None" checked />
+                <input type="submit" value="Importer pour de vrai !" class="default" style="float: none; margin: 0 auto; background: #ffee77; color: black;"/>
+                <p style="color: red;">
+                Les paiements suivants seront importés. Passez en revue les membres matchés avant de cliquer sur 'Import' !
+                </p>
+                <p>
+                N.B. : Il faut resélectionner le fichier (désolé~).
+                </p>
+                <table style="margin: 0 auto;">
+                    <tr>
+                        <th>Date</th>
+                        <th>Montant</th>
+                        <th>Libellé</th>
+                        <th>Membre matché</th>
+                    </tr>
+                {% for payment in new_payments %}
+                    <tr>
+                        <td>{{ payment.date }}</td>
+                        <td>{{ payment.amount }}</td>
+                        <td><small>{{ payment.label }}</small></td>
+                        {% if payment.member_matched %}
+                            <td>{{ payment.member_matched }}</td>
+                        {% else %}
+                            <td><span style='color: orange; font-weight: bold;'>Non matché</span></td>
+                        {% endif %}
+                    </tr>
+                {% endfor %}
+                </table>
+            {% endif %}
+        </fieldset>
+    </form>
+</div>
+{% endblock %}

+ 2 - 0
coin/billing/templates/billing/invoice.html

@@ -1,5 +1,7 @@
 {% extends "base.html" %}
 
+{% block title %}Facture N°{{ invoice.number }} - {{ block.super }}{% endblock %}
+
 {% block content %}
 <div class="row">
     <div class="large-8 columns">

+ 3 - 0
coin/billing/templates/billing/invoice_pdf.html

@@ -204,6 +204,9 @@
     </tbody>
   </table>
   <p>
+	TVA non applicable - article 293 B du CGI
+  </p>
+  <p>
     Facture à payer avant le {{ invoice.date_due }}.
   </p>
 

+ 0 - 2
coin/billing/urls.py

@@ -10,6 +10,4 @@ urlpatterns = patterns(
     url(r'^invoice/(?P<id>.+)/pdf$', views.invoice_pdf, name="invoice_pdf"),
     url(r'^invoice/(?P<id>.+)$', views.invoice, name="invoice"),
     # url(r'^invoice/(?P<id>.+)/validate$', views.invoice_validate, name="invoice_validate"),
-
-    url('invoice/create_all_members_invoices_for_a_period', views.gen_invoices)
 )

+ 2 - 9
coin/billing/views.py

@@ -3,7 +3,7 @@ from __future__ import unicode_literals
 
 from django.http import HttpResponse, HttpResponseRedirect
 from django.template import RequestContext
-from django.shortcuts import render, render_to_response
+from django.shortcuts import render
 from django.contrib import messages
 
 from sendfile import sendfile
@@ -11,15 +11,9 @@ from sendfile import sendfile
 from coin.billing.models import Invoice
 from coin.members.models import Member
 from coin.html2pdf import render_as_pdf
-from coin.billing.create_subscriptions_invoices import create_all_members_invoices_for_a_period
 from coin.billing.utils import get_invoice_from_id_or_number, assert_user_can_view_the_invoice
 
 
-def gen_invoices(request):
-    create_all_members_invoices_for_a_period()
-    return HttpResponse('blop')
-
-
 def invoice_pdf(request, id):
     """
     Renvoi une facture générée en format pdf
@@ -44,7 +38,6 @@ def invoice(request, id):
 
     assert_user_can_view_the_invoice(request, invoice)
 
-    return render_to_response('billing/invoice.html', {"invoice": invoice},
-                              context_instance=RequestContext(request))
+    return render(request, 'billing/invoice.html', {"invoice": invoice})
 
     return response

+ 2 - 0
coin/configuration/forms.py

@@ -3,12 +3,14 @@ from __future__ import unicode_literals
 
 from django.forms import ModelForm, ValidationError
 from django.db.models import Q
+from django import forms
 
 from coin.offers.models import OfferSubscription
 from coin.configuration.models import Configuration
 
 
 class ConfigurationForm(ModelForm):
+    comment = forms.CharField(widget=forms.Textarea)
 
     class Meta:
         model = Configuration

+ 1 - 0
coin/isp_database/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'coin.isp_database.app.ISPdatabaseConfig'

+ 9 - 0
coin/isp_database/app.py

@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+from django.apps import AppConfig
+
+
+class ISPdatabaseConfig(AppConfig):
+    name = 'coin.isp_database'
+    verbose_name = 'Identité du FAI'

+ 8 - 1
coin/isp_database/context_processors.py

@@ -1,9 +1,16 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 
+from django.conf import settings
+
 from coin.isp_database.models import ISPInfo
 
 def branding(request):
     """ Just a shortcut to get the ISP object in templates
     """
-    return {'branding': ISPInfo.objects.first()}
+    return {
+        'branding': ISPInfo.objects.first(),
+        'SITE_HEADER': settings.SITE_HEADER,
+        'SITE_TITLE': settings.SITE_TITLE,
+        'SITE_LOGO_URL': settings.SITE_LOGO_URL,
+    }

+ 1 - 0
coin/members/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'coin.members.app.MembersConfig'

+ 114 - 17
coin/members/admin.py

@@ -1,25 +1,24 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 
-from django.shortcuts import render, get_object_or_404
+from datetime import date
+
+from django.shortcuts import get_object_or_404
 from django.contrib import admin
 from django.contrib import messages
+from django.contrib.admin import SimpleListFilter
 from django.contrib.auth.admin import UserAdmin
-from django.contrib.auth.models import Group, Permission
 from django.contrib.contenttypes.models import ContentType
 from django.http import HttpResponseRedirect
 from django.conf.urls import url
 from django.conf import settings
-from django.db.models.query import QuerySet
 from django.core.urlresolvers import reverse
-from django.utils.html import format_html
+from django.utils.safestring import mark_safe
 
 from coin.members.models import (
     Member, CryptoKey, LdapUser, MembershipFee, Offer, OfferSubscription, RowLevelPermission)
-from coin.members.membershipfee_filter import MembershipFeeFilter
 from coin.members.forms import AdminMemberChangeForm, MemberCreationForm
 from coin.utils import delete_selected
-import autocomplete_light
 
 
 class CryptoKeyInline(admin.StackedInline):
@@ -83,12 +82,61 @@ class OfferSubscriptionInline(admin.TabularInline):
         return request.user.is_superuser
 
 
+class DataRetentionFilter(SimpleListFilter):
+    # Human-readable title which will be displayed in the
+    # right admin sidebar just above the filter options.
+    title = 'péremption des données'
+
+    # Parameter for the filter that will be used in the URL query.
+    parameter_name = 'data_cleanup'
+
+    def lookups(self, request, model_admin):
+        return (
+            ('pending_deletion', 'Pouvant légalement être supprimé'),
+        )
+
+    def queryset(self, request, queryset):
+        if self.value() == 'pending_deletion':
+            return queryset.could_be_deleted()
+
+
+class MembershipFeeFilter(SimpleListFilter):
+    # Human-readable title which will be displayed in the
+    # right admin sidebar just above the filter options.
+    title = 'Cotisations'
+
+    # Parameter for the filter that will be used in the URL query.
+    parameter_name = 'fee'
+
+    def lookups(self, request, model_admin):
+        return (
+            ('paidup', 'À jour de cotisation'),
+            ('late', 'En retard'),
+        )
+
+    def queryset(self, request, queryset):
+        if self.value() == 'paidup':
+            return queryset.paidup_fee()
+        if self.value() == 'late':
+            return queryset.no_fee_or_late()
+
+
 class MemberAdmin(UserAdmin):
-    list_display = ('id', 'status', 'username', 'first_name', 'last_name',
-                    'nickname', 'organization_name', 'email',
-                    'end_date_of_membership')
-    list_display_links = ('id', 'username', 'first_name', 'last_name')
-    list_filter = ('status', MembershipFeeFilter)
+    SERVICE_NO_FEE_MSG = (
+        "Cet·te adhérent·e bénéficie d'un service"
+        " mais n'est pas à jour de cotisation.")
+
+    RECENT_SERVICE_MSG = (
+        "Cet·te ancien·ne adhérent·e a un service résilié depuis moins d'un an"
+        ". Légalement, il faut conserver sa fiche un an après la résiliation "
+        "du service.")
+
+    list_display = ('id', 'status', 'username', 'first_name',
+                    'name_or_organization_name',
+                    'nickname', 'email',
+                    'enhanced_end_date_of_membership')
+    list_display_links = ('id', 'username', 'first_name', 'name_or_organization_name')
+    list_filter = ('status', MembershipFeeFilter, DataRetentionFilter)
     search_fields = ['username', 'first_name', 'last_name', 'email', 'nickname']
     ordering = ('status', 'username')
     actions = [delete_selected, 'set_as_member', 'set_as_non_member',
@@ -97,6 +145,47 @@ class MemberAdmin(UserAdmin):
     form = AdminMemberChangeForm
     add_form = MemberCreationForm
 
+    def name_or_organization_name(self, obj):
+        """ Used to spare some horizontal space in list view"""
+        return obj.organization_name or obj.last_name
+    name_or_organization_name.short_description = 'Nom'
+
+    def enhanced_end_date_of_membership(self, obj):
+        membership_end = obj.end_date_of_membership()
+        active_subscriptions = obj.get_active_subscriptions()
+        recent_inactive_subscriptions = obj.get_recent_inactive_subscriptions()
+
+        note = ''
+        tooltip = ''
+
+        if (membership_end is not None and membership_end < date.today()
+            and recent_inactive_subscriptions.exists() and not active_subscriptions.exists()):
+                note = ' <i class="fa fa-question-circle"  style="color: #cccc40"></i>'
+                tooltip = self.RECENT_SERVICE_MSG
+
+        if (active_subscriptions.exists() and (
+                membership_end is None or membership_end <= date.today())):
+            note = ' <i class="fa fa-question-circle"  style="color: red"></i>'
+            tooltip = self.SERVICE_NO_FEE_MSG
+
+        out = '{}{}'.format(
+            obj.end_date_of_membership() or "pas de cotisation", note)
+
+        if note:
+            return mark_safe('<span style="cursor: help;" title="{}">{}</span>'.format(tooltip, out))
+        else:
+            return mark_safe(out)
+        return mark_safe()
+    enhanced_end_date_of_membership.short_description = "Date de fin d'adhésion"
+
+    def get_list_display(self, request, obj=None):
+        list_display = list(self.list_display[:])  # Copy
+
+        if settings.HANDLE_BALANCE:
+            list_display.append('balance')
+
+        return list_display
+
     def get_fieldsets(self, request, obj=None):
         coord_fieldset = ('Coordonnées', {'fields': (
             ('email', 'send_membership_fees_email'),
@@ -145,6 +234,20 @@ class MemberAdmin(UserAdmin):
 
     inlines = [CryptoKeyInline, MembershipFeeInline, OfferSubscriptionInline]
 
+    def add_member_warnings(self, request, member):
+        has_active_subscriptions = member.get_active_subscriptions().exists()
+        has_recent_resigned_subscriptions = member.get_recent_inactive_subscriptions()
+
+        if not member.is_paid_up() and has_active_subscriptions:
+            messages.error(request, self.SERVICE_NO_FEE_MSG)
+        elif not has_active_subscriptions and has_recent_resigned_subscriptions:
+            messages.warning(request, self.RECENT_SERVICE_MSG)
+
+    def get_form(self, request, obj=None, *args, **kwargs):
+        if obj:
+            self.add_member_warnings(request, obj)
+        return super(MemberAdmin, self).get_form(request, obj, *args, **kwargs)
+
     def get_queryset(self, request):
         qs = super(MemberAdmin, self).get_queryset(request)
         if request.user.is_superuser:
@@ -258,11 +361,6 @@ class MemberAdmin(UserAdmin):
     bulk_send_call_for_membership_fee_email.short_description = 'Envoyer le courriel de relance de cotisation'
 
 
-class MembershipFeeAdmin(admin.ModelAdmin):
-    list_display = ('member', 'end_date', 'amount', 'payment_method',
-                    'payment_date')
-    form = autocomplete_light.modelform_factory(MembershipFee, fields='__all__')
-
 class RowLevelPermissionAdmin(admin.ModelAdmin):
     def get_changeform_initial_data(self, request):
         return {'content_type': ContentType.objects.get_for_model(OfferSubscription)}
@@ -270,7 +368,6 @@ class RowLevelPermissionAdmin(admin.ModelAdmin):
 
 
 admin.site.register(Member, MemberAdmin)
-admin.site.register(MembershipFee, MembershipFeeAdmin)
 # admin.site.unregister(Group)
 # admin.site.register(LdapUser, LdapUserAdmin)
 admin.site.register(RowLevelPermission, RowLevelPermissionAdmin)

+ 8 - 0
coin/members/app.py

@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+from django.apps import AppConfig
+
+class MembersConfig(AppConfig):
+    name = 'coin.members'
+    verbose_name = 'Membres'

+ 41 - 1
coin/members/forms.py

@@ -4,9 +4,49 @@ from __future__ import unicode_literals
 from django import forms
 from django.contrib.auth.forms import PasswordResetForm, ReadOnlyPasswordHashField
 from django.forms.utils import ErrorList
+from django.forms.forms import BoundField
 
 from coin.members.models import Member
 
+from registration.forms import RegistrationForm
+
+
+class MemberRegistrationForm(RegistrationForm):
+    # Protect against robot
+    trap = forms.CharField(required=False, label='Trap',
+            widget=forms.TextInput(attrs={'style' : 'display:none'}),
+        help_text="Si vous êtes humain ignorez ce champ")
+
+    def __init__(self, *args, **kwargs):
+        super(MemberRegistrationForm, self).__init__(*args, **kwargs)
+
+        for fieldname in ['email', 'organization_name', 'password2']:
+            self.fields[fieldname].help_text = None
+
+    def is_valid(self):
+         valid = super(MemberRegistrationForm,self).is_valid()
+         avoid_trap = not self.data['trap']
+         if valid and avoid_trap:
+             return True
+         else:
+             return False
+
+    def as_p(self):
+        """"
+        We rewrite the as_p method to apply a style on the <p> tag related to
+        trap field. Indeed, it seeems there is no cleaner way to do it.
+        """
+        def css_classes(self, extra_classes=None):
+            return 'captcha'
+
+        func_type = type(BoundField.css_classes)
+        self['trap'].css_classes = func_type(css_classes, self, BoundField)
+        return super(MemberRegistrationForm, self).as_p()
+
+    class Meta:
+        model = Member
+        fields = ['type', 'first_name', 'last_name',
+                  'organization_name', 'email', 'username', 'trap']
 
 class MemberCreationForm(forms.ModelForm):
 
@@ -106,7 +146,7 @@ class OrganizationMemberChangeForm(AbstractMemberChangeForm):
                   'address', 'postal_code', 'city', 'country']
 
     def __init__(self, *args, **kwargs):
-        super(OrganizationChangeForm, self).__init__(*args, **kwargs)
+        super(OrganizationMemberChangeForm, self).__init__(*args, **kwargs)
         self.error_class = SpanError
         for fieldname in self.fields:
             self.fields[fieldname].help_text = None

+ 4 - 5
coin/members/management/commands/call_for_membership_fees.py

@@ -30,11 +30,10 @@ class Command(BaseCommand):
             raise CommandError(
                 'Please enter a valid date : YYYY-mm-dd (ex: 2011-07-04)')
 
-        end_dates = [date + relativedelta(months=-3),
-                     date + relativedelta(months=-2),
-                     date + relativedelta(months=-1),
-                     date,
-                     date + relativedelta(months=+1)]
+        end_dates = [
+            date + relativedelta(**params)
+            for params in settings.MEMBERSHIP_FEE_REMINDER_DATES
+        ]
 
         if verbosity >= 2:
             self.stdout.write("Selecting members whose membership fee end at "

+ 0 - 42
coin/members/membershipfee_filter.py

@@ -1,42 +0,0 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
-from django.contrib.admin import SimpleListFilter
-import datetime
-
-
-class MembershipFeeFilter(SimpleListFilter):
-    # Human-readable title which will be displayed in the
-    # right admin sidebar just above the filter options.
-    title = 'Cotisations'
-
-    # Parameter for the filter that will be used in the URL query.
-    parameter_name = 'fee'
-
-    def lookups(self, request, model_admin):
-        """
-        Returns a list of tuples. The first element in each
-        tuple is the coded value for the option that will
-        appear in the URL query. The second element is the
-        human-readable name for the option that will appear
-        in the right sidebar.
-        """
-        return (
-            ('paidup', 'À jour de cotisation'),
-            ('late', 'En retard'),
-        )
-
-    def queryset(self, request, queryset):
-        """
-        Returns the filtered queryset based on the value
-        provided in the query string and retrievable via
-        `self.value()`.
-        """
-        if self.value() == 'paidup':
-            return queryset.filter(
-                membership_fees__start_date__lte=datetime.date.today,
-                membership_fees__end_date__gte=datetime.date.today)
-        if self.value() == 'late':
-            return queryset.filter(status='member').exclude(
-                membership_fees__start_date__lte=datetime.date.today,
-                membership_fees__end_date__gte=datetime.date.today)

+ 1 - 1
coin/members/migrations/0003_auto_20141007_0956.py

@@ -14,7 +14,7 @@ class Migration(migrations.Migration):
         migrations.AlterField(
             model_name='membershipfee',
             name='amount',
-            field=models.IntegerField(default=settings.MEMBER_DEFAULT_COTISATION, help_text='en \u20ac', verbose_name='montant'),
+            field=models.IntegerField(default=settings.DEFAULT_MEMBERSHIP_FEE, help_text='en \u20ac', verbose_name='montant'),
         ),
         migrations.AlterField(
             model_name='membershipfee',

+ 1 - 1
coin/members/migrations/0004_auto_20141007_1002.py

@@ -15,6 +15,6 @@ class Migration(migrations.Migration):
         migrations.AlterField(
             model_name='membershipfee',
             name='amount',
-            field=models.DecimalField(default=settings.MEMBER_DEFAULT_COTISATION, help_text='en \u20ac', verbose_name='montant', max_digits=5, decimal_places=2),
+            field=models.DecimalField(default=settings.DEFAULT_MEMBERSHIP_FEE, help_text='en \u20ac', verbose_name='montant', max_digits=5, decimal_places=2),
         ),
     ]

+ 23 - 0
coin/members/migrations/0018_auto_20180819_0211.py

@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('members', '0017_merge'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='rowlevelpermission',
+            options={'verbose_name': 'permission fine', 'verbose_name_plural': 'permissions fines'},
+        ),
+        migrations.AlterModelManagers(
+            name='member',
+            managers=[
+            ],
+        ),
+    ]

+ 71 - 8
coin/members/models.py

@@ -10,21 +10,48 @@ from django.db.models import Q, Max
 from django.db.models.signals import pre_save
 from django.dispatch import receiver
 from django.contrib.auth.models import AbstractUser, Permission, UserManager
-from django.contrib.contenttypes.models import ContentType
 from django.conf import settings
 from django.core.validators import RegexValidator
 from django.core.exceptions import ValidationError
 from django.utils import timezone
 from django.utils.text import slugify
+from django.core.mail import send_mail
+from django.core.urlresolvers import reverse
 from ldapdb.models.fields import CharField, IntegerField, ListField
+from registration.signals import user_registered
 
 from coin.offers.models import Offer, OfferSubscription
 from coin.mixins import CoinLdapSyncMixin
 from coin import utils
 
 
+class MemberQuerySet(models.QuerySet):
+    paidup_q = Q(
+        # we have at least one fee
+        membership_fees__isnull=False,
+        # and it is still running
+        membership_fees__end_date__gte=datetime.date.today)
+
+    def paidup_fee(self):
+        return self.filter(self.paidup_q)
+
+    def no_fee_or_late(self):
+        return self.exclude(self.paidup_q)
+
+    def could_be_deleted(self):
+        return self.exclude(
+            # we have at least one subscription
+            Q(offersubscription__isnull=False),
+            # still running or  resigned less than one year ago
+            Q(offersubscription__resign_date__isnull=True)
+            |
+            Q(offersubscription__resign_date__gte=utils.one_year_ago())
+        ).exclude(self.paidup_q)
+
 
 class MemberManager(UserManager):
+    use_in_migrations = False
+
     def manageable_by(self, user):
         """" Renvoie la liste des members que l'utilisateur est autorisé à voir
         dans l'interface d'administration.
@@ -35,6 +62,21 @@ class MemberManager(UserManager):
             offers = Offer.objects.manageable_by(user)
             return super(MemberManager, self).filter(offersubscription__offer__in=offers).distinct()
 
+@receiver(user_registered)
+def send_registration_notification(sender, user, request=None, **kwargs):
+    """
+    Send a notification to the admin if a user subscribe
+    """
+    relative_link = reverse('admin:members_member_change', args=[user.id])
+    edit_link = request.build_absolute_uri(relative_link)
+    if settings.SUBSCRIPTIONS_NOTIFICATION_EMAILS:
+        utils.send_templated_email(
+            to=settings.SUBSCRIPTIONS_NOTIFICATION_EMAILS,
+            subject_template='members/emails/new_member_email_subject.txt',
+            body_template='members/emails/new_member_email.html',
+            context={'member': user, 'edit_link': edit_link},
+        )
+
 
 class Member(CoinLdapSyncMixin, AbstractUser):
 
@@ -45,10 +87,15 @@ class Member(CoinLdapSyncMixin, AbstractUser):
         ('natural_person', 'Personne physique'),
         ('legal_entity', 'Personne morale'),
     )
+
+    MEMBER_STATUS_MEMBER = 'member'
+    MEMBER_STATUS_NOT_MEMBER = 'not_member'
+    MEMBER_STATUS_PENDING = 'pending'
+
     MEMBER_STATUS_CHOICES = (
-        ('member', 'Adhérent'),
-        ('not_member', 'Non adhérent'),
-        ('pending', "Demande d'adhésion"),
+        (MEMBER_STATUS_MEMBER, 'Adhérent'),
+        (MEMBER_STATUS_NOT_MEMBER, 'Non adhérent'),
+        (MEMBER_STATUS_PENDING, "Demande d'adhésion"),
     )
 
     status = models.CharField(max_length=50, choices=MEMBER_STATUS_CHOICES,
@@ -94,9 +141,9 @@ class Member(CoinLdapSyncMixin, AbstractUser):
         default=True, verbose_name='relance de cotisation',
         help_text='Précise si l\'utilisateur doit recevoir des mails de relance pour la cotisation. Certains membres n\'ont pas à recevoir de relance (prélèvement automatique, membres d\'honneurs, etc.)')
     balance = models.DecimalField(max_digits=5, decimal_places=2, default=0,
-                                  verbose_name='account balance')
+                                  verbose_name='solde')
 
-    objects = MemberManager()
+    objects = MemberManager.from_queryset(MemberQuerySet)()
 
     # Following fields are managed by the parent class AbstractUser :
     # username, first_name, last_name, email
@@ -178,6 +225,15 @@ class Member(CoinLdapSyncMixin, AbstractUser):
             Q(subscription_date__gt=date) |
             Q(resign_date__lt=date))
 
+    def get_recent_inactive_subscriptions(self):
+        """ Does this member has subscriptions that ended less than one year ago
+
+        For French law requirements.
+        """
+        return self.get_inactive_subscriptions().filter(
+            resign_date__gte=datetime.date.today() - datetime.timedelta(days=365))
+
+
     def get_ssh_keys(self):
         # Quick & dirty, ensure that keys are unique (otherwise, LDAP complains)
         return list({k.key for k in self.cryptokey_set.filter(type='RSA')})
@@ -331,7 +387,6 @@ class Member(CoinLdapSyncMixin, AbstractUser):
 
         return False
 
-
     class Meta:
         verbose_name = 'membre'
 
@@ -430,7 +485,7 @@ class MembershipFee(models.Model):
     member = models.ForeignKey('Member', related_name='membership_fees',
                                verbose_name='membre')
     amount = models.DecimalField(null=False, max_digits=5, decimal_places=2,
-                                 default=settings.MEMBER_DEFAULT_COTISATION,
+                                 default=settings.DEFAULT_MEMBERSHIP_FEE,
                                  verbose_name='montant', help_text='en €')
     start_date = models.DateField(
         null=False,
@@ -456,6 +511,14 @@ class MembershipFee(models.Model):
         if self.start_date is not None and self.end_date is None:
             self.end_date = self.start_date + datetime.timedelta(364)
 
+    def save(self, *args, **kwargs):
+        ret = super(MembershipFee, self).save(*args, **kwargs)
+        today = datetime.date.today()
+        if self.start_date <= today and today <= self.end_date:
+            self.member.status = self.member.MEMBER_STATUS_MEMBER
+            self.member.save()
+        return ret
+
     def __unicode__(self):
         return '%s - %s - %i€' % (self.member, self.start_date, self.amount)
 

+ 21 - 0
coin/members/registration_views.py

@@ -0,0 +1,21 @@
+from registration.backends.hmac.views import ActivationView, RegistrationView
+
+
+class MemberActivationView(ActivationView):
+    template_name = 'members/registration/activate.html'
+    def get_success_url(self, user):
+        return ('members:registration_activation_complete', (), {})
+
+class MemberRegistrationView(RegistrationView):
+    success_url = ('member:registration_activation_complete', (), {})
+    email_subject_template = 'members/registration/activation_email_subject.txt'
+    email_body_template = 'members/registration/activation_email.txt'
+    template_name = 'members/registration/registration_form.html'
+
+    def register(self, form):
+        new_user = super(MemberRegistrationView, self).register(form)
+        new_user.status = new_user.MEMBER_STATUS_PENDING
+        return new_user.save()
+
+    def get_success_url(self, user):
+        return ('members:registration_complete', (), {})

+ 4 - 1
coin/members/templates/admin/members/member/change_form.html

@@ -1,6 +1,9 @@
 {% extends "admin/change_form.html" %}
 {% load url from future %}
 {% block object-tools-items %}
-    <li><a href="{% url 'admin:send_welcome_email' id=object_id %}" onclick="return confirm('Voulez-vous vraiment envoyer le courriel de confirmation a ce membre ?');">Envoyer le courriel de bienvenue</a></li>
+    <li><a href="{% url 'admin:send_welcome_email' id=object_id %}" onclick="return confirm('Voulez-vous vraiment envoyer le courriel de confirmation à ce membre ?');">Envoyer le courriel de bienvenue</a></li>
+    {% if request.user.is_superuser %}
+    <li><a href="{% url 'hijack:login_with_id' user_id=object_id %}">Endosser temporairement cette identité</a></li>
+    {% endif %}
     {{ block.super }}
 {% endblock %}

+ 39 - 0
coin/members/templates/admin/members/member/delete_confirmation.html

@@ -0,0 +1,39 @@
+{% extends "admin/delete_confirmation.html" %}
+{% block content %}
+<ul class="messagelist">
+    {% if object.get_active_subscriptions.exists %}
+    <li class="warning">
+        Cet·te adhérent·e possède un abonnement à un service en
+        cours
+
+        ({% for i in object.get_active_subscriptions %}{{ i.offer.name }}{% if not forloop.last %}, {% endif %}{% endfor %}).
+
+        Légalement, il faut conserver sa fiche un an après la résiliation du service.
+    </li>
+    {% endif %}
+
+    {% if object.get_recent_inactive_subscriptions.exists %}
+    <li class="warning">
+        Cet·te adhérent·e possède un service résilié depuis moins d'un
+        an
+        ({% for i in object.get_recent_inactive_subscriptions %}{{ i.offer.name }}{% if not forloop.last %}, {% endif %}{% endfor %}).
+
+        Légalement, il faut conserver sa fiche un an après la résiliation
+        du service.
+    </li>
+    {% endif %}
+
+    {% if object.loans.running.exists %}
+    <li class="warning">
+        Cet·te adhérent·e possède du matériel non rendu :
+        {% for i in object.loans.running %}
+          {{ i.item }}{% if not forloop.last %}, {% endif %}
+        {% endfor %}.
+        Vous devriez terminer ces emprunts et vous assurer
+        que le matériel a été rendu.
+    </li>
+    {% endif %}
+</ul>
+
+{{ block.super }}
+{% endblock %}

+ 1 - 0
coin/members/templates/members/contact.html

@@ -1,4 +1,5 @@
 {% extends "base.html" %}
+{% block title %}Contact / Support - {{ block.super }}{% endblock %}
 
 {% block content %}
 <div class="row">

+ 2 - 0
coin/members/templates/members/detail.html

@@ -1,5 +1,7 @@
 {% extends "base.html" %}
 
+{% block title %}Mes informations - {{ block.super }}{% endblock %}
+
 {% block content %}
 <div class="row">
     <div class="large-12 columns">

+ 9 - 0
coin/members/templates/members/emails/new_member_email.html

@@ -0,0 +1,9 @@
+Bonjour,<br />
+
+<p>{{ member }} s'est enregistré⋅e sur l'espace adhérent
+(COIN).</p>
+
+<p>Lien d'édition: <a href="{{ edit_link }}">{{ edit_link }}</a></p>
+
+Bisou,
+Votre canard dévoué

+ 1 - 0
coin/members/templates/members/emails/new_member_email_subject.txt

@@ -0,0 +1 @@
+[COIN] Nouveau compte créé

+ 2 - 0
coin/members/templates/members/index.html

@@ -1,5 +1,7 @@
 {% extends "base.html" %}
 
+{% block title %}Tableau de bord - {{ block.super }}{% endblock %}
+
 {% block content %}
 <div class="row">
     <div class="large-12 columns">

+ 3 - 1
coin/members/templates/members/invoices.html

@@ -1,9 +1,11 @@
 {% extends "base.html" %}
 
+{% block title %}Factures & paiements - {{ block.super }}{% endblock %}
+
 {% block content %}
 
 {% if handle_balance %}
-	<h2>Balance : {{ balance|floatformat }} €</h2>
+	<h2>Solde : {{ balance|floatformat }} €</h2>
 {% endif %}
 
 <h2>Mes factures</h2>

+ 10 - 0
coin/members/templates/members/registration/activate.html

@@ -0,0 +1,10 @@
+{% extends "base.html" %}
+{% load i18n %}
+
+{% block title %}Activation échouée - {{ block.super }}{% endblock %}
+
+{% block content %}
+
+<p>L'activation de votre compte a échoué ou ce dernier a déjà été activé.</p>
+
+{% endblock %}

+ 20 - 0
coin/members/templates/members/registration/activation_complete.html

@@ -0,0 +1,20 @@
+{% extends "base.html" %}
+{% load i18n %}
+
+{% block title %}Compte créé - {{ block.super }}{% endblock %}
+
+{% block content %}
+
+<h2>Compte adhérent créé</h2>
+{% if dues %}
+    <p>Votre compte adhérent est désormais créé, pour finaliser votre adhésion merci d'<b>envoyer votre adhésion de {{ dues }} €</b> par virement  avec le libellé suivant:&nbsp;<b>{{ bank_transfer_label }}</b> .</p>
+
+    <h2>Coordonnées bancaires</h2>
+    <div id="payment-howto" class="panel">
+        {% include "billing/payment_howto.html" %}
+    </div>
+{% else %}
+    <p>Votre compte adhérent est désormais créé.</p>
+{% endif %}
+
+{% endblock %}

+ 12 - 0
coin/members/templates/members/registration/activation_email.txt

@@ -0,0 +1,12 @@
+{% load i18n %}
+Bonjour,
+
+Pour activer votre compte adhérent {{ site.name }}, merci de suivre le lien suivant:
+
+http://{{ site.domain }}{% url 'members:registration_activate' activation_key %}
+
+{% blocktrans %}Ce lien sera valable pendant {{ expiration_days }} jours.{% endblocktrans %}
+
+Ceci est un courriel automatique envoyé à la suite d'une demande de création de compte.
+
+L'équipe de l'association {{ branding.shortname|capfirst }}

+ 1 - 0
coin/members/templates/members/registration/activation_email_subject.txt

@@ -0,0 +1 @@
+{% load i18n %}Activation de votre compte adhérent {{ site.name }}

+ 13 - 4
coin/members/templates/members/registration/login.html

@@ -1,6 +1,8 @@
 {% extends "base.html" %}
 {% load i18n %}
 
+{% block title %}Connexion - {{ block.super }}{% endblock %}
+
 {% block content %}
 
 <div class="row">
@@ -39,14 +41,21 @@
             <input type="submit" value="Connexion" class="button radius"/>
             <input type="hidden" name="next" value="{{ next }}" />
             <a id="password-reset-link" href="{% url 'members:password_reset' %}" tabindex="100">Mot de passe oublié ?</a>
+            {% if settings.REGISTRATION_OPEN  %}
+                / <a href="{% url 'members:registration_register' %}">Créer un compte</a>
+            {% endif %}
         </form>
     </div>
     <div class="medium-5 columns">
         <div class="panel callout" id="newcomers">
-            <h3>Nouvel adhérent ?</h3>
-            <p>Pour votre première connexion, il faut définir votre mot de passe.<br />
-            <a href="{% url 'members:password_reset' %}"><i class="fa fa-arrow-right"></i>
- Initialiser mon mot de passe</a></p>
+                {% if not settings.REGISTRATION_OPEN  %}
+                    <h3>Nouvel adhérent⋅e ?</h3>
+                    <p>Pour votre première connexion, il faut définir votre mot de passe.<br />
+                {% else %}
+                    <h3>Première connexion</h3>
+                    <p>Si un·e bénévole a déjà créé votre compte, il faut commencer par choisir votre mot de passe.<br />
+                {% endif %}
+                <a href="{% url 'members:password_reset' %}"><i class="fa fa-arrow-right"></i> Initialiser mon mot de passe</a></p>
         </div>
     </div>
 

+ 3 - 0
coin/members/templates/members/registration/password_change_base.html

@@ -0,0 +1,3 @@
+{% extends "base.html" %}
+
+{% block title %}Modification du mot de passe - {{ block.super }}{% endblock %}

+ 1 - 3
coin/members/templates/members/registration/password_change_done.html

@@ -1,8 +1,6 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_change_base.html" %}
 {% load i18n %}
 
-{% block title %}{% trans 'Password change successful' %}{% endblock %}
-
 {% block content %}
 <div class="row">
     <div class="large-12 columns">

+ 3 - 2
coin/members/templates/members/registration/password_change_form.html

@@ -1,4 +1,5 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_change_base.html" %}
+
 {% load i18n static %}
 
 {% block content %}
@@ -45,4 +46,4 @@
 
 <script type="text/javascript">document.getElementById("id_old_password").focus();</script>
 
-{% endblock %}
+{% endblock %}

+ 3 - 0
coin/members/templates/members/registration/password_reset_base.html

@@ -0,0 +1,3 @@
+{% extends "base.html" %}
+
+{% block title %}Ré-initialisation du mot de passe - {{ block.super }}{% endblock %}

+ 1 - 1
coin/members/templates/members/registration/password_reset_complete.html

@@ -1,4 +1,4 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_reset_base.html" %}
 {% load i18n %}
 
 {% block content %}

+ 1 - 1
coin/members/templates/members/registration/password_reset_confirm.html

@@ -1,4 +1,4 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_reset_base.html" %}
 {% load i18n %}
 
 {% block content %}

+ 2 - 1
coin/members/templates/members/registration/password_reset_done.html

@@ -1,4 +1,5 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_reset_base.html" %}
+
 {% load i18n %}
 
 {% block content %}

+ 1 - 1
coin/members/templates/members/registration/password_reset_form.html

@@ -1,4 +1,4 @@
-{% extends "base.html" %}
+{% extends "members/registration/password_reset_base.html" %}
 {% load staticfiles %}
 {% load i18n %}
 

+ 3 - 0
coin/members/templates/members/registration/registration_base.html

@@ -0,0 +1,3 @@
+{% extends "base.html" %}
+
+{% block title %}Création de compte - {{ block.super }}{% endblock %}

+ 6 - 0
coin/members/templates/members/registration/registration_closed.html

@@ -0,0 +1,6 @@
+{% extends "members/registration/registration_base.html" %}
+{% load i18n %}
+
+{% block content %}
+	<p>{% trans "Registration is currently closed." %}</p>
+{% endblock %}

+ 6 - 0
coin/members/templates/members/registration/registration_complete.html

@@ -0,0 +1,6 @@
+{% extends "members/registration/registration_base.html" %}
+{% load i18n %}
+
+{% block content %}
+<p>Votre demande de création de compte a été enregistrée. Afin de finaliser la création du compte, un email d'activation vous a été envoyé.</p>
+{% endblock %}

+ 66 - 0
coin/members/templates/members/registration/registration_form.html

@@ -0,0 +1,66 @@
+{% extends "members/registration/registration_base.html" %}
+
+{% load i18n %}
+
+{% block content %}
+        <h2>Créer un compte adhérent</h2>
+<div class="row">
+    <div class="medium-4 large-4 columns">
+        <div class="panel callout">
+            <h3>Déjà un compte ?</h3>
+            <p>Il est possible qu'un bénévole ait déjà créé votre compte.</p><p>Dans ce cas pour votre première connexion, il faut commencer par choisir votre mot de passe.<br />
+            <a href="{% url 'members:password_reset' %}"><i class="fa fa-arrow-right"></i> Initialiser mon mot de passe</a></p>
+        
+        <a href="{% url 'members:login' %}"><i class="fa fa-arrow-right"></i> OU essayer de me connecter</a>
+        </div>
+    </div>
+
+    <div class="medium-8 large-8 columns">
+        <form method="post" action=".">
+        
+            {% csrf_token %}
+            <fieldset class="module aligned wide">
+            {{ form.as_p }}
+            </fieldset>
+        <input type="submit" class="button radius" value="Créer mon compte" />
+        </form>
+    </div>
+</div>
+{% endblock %}
+{% block extra_js %}
+<script>
+$(document).ready(function () {
+  var hideFields=function(){
+    var optionSelected = $("option:selected", this);
+    var valueSelected = this.value;
+    if (valueSelected == 'legal_entity') {
+      $('#id_first_name').parent().hide();
+      $('#id_last_name').parent().hide();
+      $('#id_organization_name').parent().show();
+      $('#id_first_name').val('');
+      $('#id_last_name').val('');
+    } else if (valueSelected == 'natural_person') {
+      $('#id_organization_name').parent().hide();
+      $('#id_first_name').parent().show();
+      $('#id_last_name').parent().show();
+      $('#id_organization_name').val('');
+    }
+    return false;
+  };
+  $('#id_type').on('change', hideFields);
+  if (!$('#id_organization_name').val()) {
+    $('#id_type').val('natural_person');
+      $('#id_organization_name').parent().hide();
+      $('#id_first_name').parent().show();
+      $('#id_last_name').parent().show();
+  }
+  else {
+    $('#id_type').val('legal_entity');
+      $('#id_first_name').parent().hide();
+      $('#id_last_name').parent().hide();
+      $('#id_organization_name').parent().show();
+  }
+});
+</script>
+
+{% endblock %}

+ 2 - 0
coin/members/templates/members/subscriptions.html

@@ -1,5 +1,7 @@
 {% extends "base.html" %}
 
+{% block title %}Mes abonnements - {{ block.super }}{% endblock %}
+
 {% block content %}
 <h2>Mes abonnements</h2>
 

+ 69 - 5
coin/members/tests.py

@@ -2,21 +2,23 @@
 from __future__ import unicode_literals
 
 import os
-import logging
+
 import ldapdb
 from datetime import date
 from cStringIO import StringIO
 from dateutil.relativedelta import relativedelta
+from freezegun import freeze_time
 import unittest
+from freezegun import freeze_time
 
 from django import db
 from django.conf import settings
-from django.test import TestCase, Client, override_settings
-from django.contrib.auth.models import User
+from django.test import TestCase, Client
 from django.core import mail, management
 from django.core.exceptions import ValidationError
 
 from coin.members.models import Member, MembershipFee, LdapUser
+from coin.offers.models import OfferSubscription, Offer
 from coin.validation import chatroom_url_validator
 
 
@@ -359,6 +361,21 @@ class MemberTests(TestCase):
         # de cotisation
         self.assertEqual(member.is_paid_up(), True)
 
+    @freeze_time('2016-01-01')
+    def test_adding_running_fee_set_membership_status(self):
+        member = Member.objects.create(
+            first_name='a', last_name='b', username='c',
+            status=Member.MEMBER_STATUS_PENDING)
+
+        # Créé une cotisation passée
+        MembershipFee.objects.create(
+            member=member, amount=20,
+            start_date=date(2015, 12, 12),
+            end_date=date(2016, 12, 12))
+
+        member = Member.objects.get(pk=member.pk)
+        self.assertEqual(member.status, member.MEMBER_STATUS_MEMBER)
+
     def test_member_cant_be_created_without_names(self):
         """
         Test qu'un membre ne peut pas être créé sans "noms"
@@ -494,6 +511,52 @@ class MemberTestCallForMembershipCommand(TestCase):
         self.do_test_email_sent(0)
 
 
+class MemberManagerTest(TestCase):
+    def setUp(self):
+        self.ab = Member.objects.create(
+            first_name='a', last_name='b', username='ab', email='ab@ex.com')
+        self.cd = Member.objects.create(
+            first_name='c', last_name='d', username='cd', email='cd@ex.com')
+        self.ef = Member.objects.create(
+            first_name='e', last_name='f', username='ef', email='ef@ex.com')
+        self.gh = Member.objects.create(
+            first_name='g', last_name='h', username='gh', email='gh@ex.com')
+
+        MembershipFee.objects.create(member=self.ab, amount=20,
+                      start_date=date(2015, 11, 11),
+                      end_date=date(2016, 11, 11))
+
+        MembershipFee.objects.create(member=self.cd, amount=20,
+                      start_date=date(2016, 1, 1),
+                      end_date=date(2016, 1, 1))
+
+        OfferSubscription.objects.create(
+            subscription_date=date(2016, 2, 2),
+            member=self.ef,
+            offer=Offer.objects.create(
+                name='fu',
+                period_fees=0,
+                initial_fees=0
+            ),
+        )
+
+    @freeze_time('2016-10-01')
+    def test_could_be_deleted(self):
+        deletion_set = set(Member.objects.could_be_deleted())
+
+        # late on fee (-> delete)
+        self.assertIn(self.cd, deletion_set)
+
+        # no fee at all (-> delete)
+        self.assertIn(self.gh, deletion_set)
+
+        # running fee (-> no delete)
+        self.assertNotIn(self.ab, deletion_set)
+
+        # running service (even if no fee) (-> no delete)
+        self.assertNotIn(self.ef, deletion_set)
+
+
 class MemberTestsUtils(object):
 
     @staticmethod
@@ -518,12 +581,13 @@ class MembershipFeeTests(TestCase):
 
         # If there is no start_date clean_fields() should raise an
         # error but not clean().
-        membershipfee = MembershipFee(member=member)
+        membershipfee = MembershipFee(member=member, amount=15)
         self.assertRaises(ValidationError, membershipfee.clean_fields)
         self.assertIsNone(membershipfee.clean())
 
         # If there is a start_date, everything is fine.
-        membershipfee = MembershipFee(member=member, start_date=date.today())
+        membershipfee = MembershipFee(member=member, amount=15,
+                start_date=date.today())
         self.assertIsNone(membershipfee.clean_fields())
         self.assertIsNone(membershipfee.clean())
 

+ 44 - 3
coin/members/urls.py

@@ -2,16 +2,29 @@
 from __future__ import unicode_literals
 
 from django.conf.urls import patterns, url
-from django.views.generic import DetailView
+from coin.members import forms
 from coin.members import views
-from coin.members.models import Member
+from django.views.generic.base import TemplateView
+from . import registration_views as views_r
+from coin import settings
 
+from registration.signals import user_activated
+from django.contrib.auth import login
+
+def login_on_activation(sender, user, request, **kwargs):
+    """Logs in the user after activation"""
+    user.backend = 'django.contrib.auth.backends.ModelBackend'
+    login(request, user)
+
+# Registers the function with the django-registration user_activated signal
+user_activated.connect(login_on_activation)
 
 urlpatterns = patterns(
     '',
     url(r'^$', views.index, name='index'),
     url(r'^login/$', 'django.contrib.auth.views.login',
-        {'template_name': 'members/registration/login.html'},
+        {'template_name': 'members/registration/login.html',
+         'extra_context': {'settings': settings} },
         name='login'),
     url(r'^logout/$', 'django.contrib.auth.views.logout_then_login',
         name='logout'),
@@ -43,6 +56,34 @@ urlpatterns = patterns(
         name='password_reset_complete'),
 
 
+    url(r'^activate/complete/$', views.activation_completed,
+        name='registration_activation_complete'),
+    # The activation key can make use of any character from the
+    # URL-safe base64 alphabet, plus the colon as a separator.
+    url(r'^activate/(?P<activation_key>[-:\w]+)/$',
+        views_r.MemberActivationView.as_view(),
+        name='registration_activate'),
+    url(r'^register/$',
+        views_r.MemberRegistrationView.as_view(
+            form_class=forms.MemberRegistrationForm,
+            template_name='members/registration/registration_form.html'
+        ),
+        name='registration_register'),
+    url(r'^register/complete/$',
+        TemplateView.as_view(
+            template_name='members/registration/registration_complete.html'
+        ),
+        name='registration_complete'),
+    url(r'^register/closed/$',
+        TemplateView.as_view(
+            template_name='members/registration/registration_closed.html'
+        ),
+        name='registration_disallowed'),
+    #url(r'', include('registration.auth_urls')),
+
+
+
+
     url(r'^detail/$', views.detail,
         name='detail'),
 

+ 24 - 17
coin/members/views.py

@@ -2,18 +2,16 @@
 from __future__ import unicode_literals
 
 from django.template import RequestContext
-from django.shortcuts import render_to_response, render
+from django.shortcuts import render
 from django.contrib.auth.decorators import login_required
-from django.http import Http404
 from django.conf import settings
 from forms import PersonMemberChangeForm, OrganizationMemberChangeForm
 
 @login_required
 def index(request):
     has_isp_feed = 'isp' in [k for k, _, _ in settings.FEEDS]
-    return render_to_response('members/index.html',
-                              {'has_isp_feed': has_isp_feed},
-                              context_instance=RequestContext(request))
+    return render(request, 'members/index.html',
+                  {'has_isp_feed': has_isp_feed})
 
 
 @login_required
@@ -47,10 +45,9 @@ def subscriptions(request):
     subscriptions = request.user.get_active_subscriptions()
     old_subscriptions = request.user.get_inactive_subscriptions()
 
-    return render_to_response('members/subscriptions.html',
-                              {'subscriptions': subscriptions,
-                               'old_subscriptions': old_subscriptions},
-                              context_instance=RequestContext(request))
+    return render(request, 'members/subscriptions.html',
+                  {'subscriptions': subscriptions,
+                   'old_subscriptions': old_subscriptions})
 
 
 @login_required
@@ -59,15 +56,25 @@ def invoices(request):
     invoices = request.user.invoices.filter(validated=True).order_by('-date')
     payments = request.user.payments.filter().order_by('-date')
 
-    return render_to_response('members/invoices.html',
-                              {'balance' : balance, 
-                               'handle_balance' : settings.HANDLE_BALANCE, 
-                               'invoices': invoices, 
-                               'payments': payments},
-                              context_instance=RequestContext(request))
+    return render(request, 'members/invoices.html',
+                              {'balance' : balance,
+                               'handle_balance' : settings.HANDLE_BALANCE,
+                               'invoices': invoices,
+                               'payments': payments})
 
 
 @login_required
 def contact(request):
-    return render_to_response('members/contact.html',
-                              context_instance=RequestContext(request))
+    return render(request, 'members/contact.html')
+
+
+@login_required
+def activation_completed(request):
+    label_template = settings.MEMBERSHIP_REFERENCE.format(user=request.user)
+    context = {
+        'bank_transfer_label': label_template,
+        'dues': settings.DEFAULT_MEMBERSHIP_FEE
+    }
+
+    return render(request, 'members/registration/activation_complete.html',
+                  context)

+ 2 - 0
coin/mixins.py

@@ -4,6 +4,8 @@ from __future__ import unicode_literals
 from django.db import transaction
 from django.conf import settings
 
+from django.views.generic import TemplateView
+
 
 class CoinLdapSyncMixin(object):
 

+ 1 - 0
coin/offers/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'coin.offers.app.OffersConfig'

+ 9 - 0
coin/offers/app.py

@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+from django.apps import AppConfig
+
+
+class OffersConfig(AppConfig):
+    name = 'coin.offers'
+    verbose_name = 'Offres et Abonnements'

+ 11 - 0
coin/offers/fixtures/offers.json

@@ -53,5 +53,16 @@
             "period_fees": "28.00",
             "configuration_type": ""
         }
+    },
+    {
+        "pk": 6,
+        "model": "offers.offer",
+        "fields": {
+            "billing_period": 1,
+            "name": "VPS 1Go",
+            "initial_fees": "0.00",
+            "period_fees": "8.00",
+            "configuration_type": "VPSConfiguration"
+        }
     }
 ]

+ 67 - 1
coin/settings_base.py

@@ -16,6 +16,9 @@ ADMINS = (
     # ('Your Name', 'your_email@example.com'),
 )
 
+# Email on which to send emails
+SUBSCRIPTIONS_NOTIFICATION_EMAILS = []
+
 MANAGERS = ADMINS
 
 DATABASES = {
@@ -118,6 +121,7 @@ TEMPLATE_LOADERS = (
 )
 
 MIDDLEWARE_CLASSES = (
+    'debug_toolbar.middleware.DebugToolbarMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
@@ -127,6 +131,14 @@ MIDDLEWARE_CLASSES = (
     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 )
 
+# Do not load jQuery from crappy CDN
+DEBUG_TOOLBAR_CONFIG = {
+    'JQUERY_URL': '/static/js/vendor/jquery.js'
+}
+
+# Used for debug toolbar
+INTERNAL_IPS = ['127.0.0.1', '::1']
+
 ROOT_URLCONF = 'coin.urls'
 
 # Python dotted path to the WSGI application used by Django's runserver.
@@ -140,6 +152,7 @@ TEMPLATE_DIRS = (
 EXTRA_TEMPLATE_DIRS = tuple()
 
 INSTALLED_APPS = (
+    'debug_toolbar',  # always installed, but enabled only if DEBUG=True
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
@@ -156,6 +169,9 @@ INSTALLED_APPS = (
     # 'south',
     'autocomplete_light', #Automagic autocomplete foreingkey form component
     'activelink', #Detect if a link match actual page
+    'compat',
+    'hijack',
+
     'coin',
     'coin.members',
     'coin.offers',
@@ -230,6 +246,15 @@ AUTHENTICATION_BACKENDS = (
 
 TEST_RUNNER = 'django.test.runner.DiscoverRunner'
 
+# Where admins are redirected to after hijacking a user
+HIJACK_LOGIN_REDIRECT_URL = '/'
+
+# Where admins are redirected to after releasing a user
+HIJACK_LOGOUT_REDIRECT_URL = '/admin/members/member/'
+
+# Needed for link in admin
+HIJACK_ALLOW_GET_REQUESTS = True
+
 GRAPHITE_SERVER = "http://localhost"
 
 # Configuration for outgoing emails
@@ -244,18 +269,42 @@ LDAP_ACTIVATE = False
 LDAP_USER_BASE_DN = None
 VPN_CONF_BASE_DN = None
 
+# Allow member to edit their vpn
+MEMBER_CAN_EDIT_VPN_CONF = True
+
 # Membership configuration
 # Default cotisation in €, per year
-MEMBER_DEFAULT_COTISATION = 20
+DEFAULT_MEMBERSHIP_FEE = 20
 
 # Link to a page with information on how to become a member or pay the
 # membership fee
 MEMBER_MEMBERSHIP_INFO_URL = ''
 
+
+# When should we remind a member about its membership ?  List of deltas from
+# the anniversary date, can be a combination of positive (after anniversary)
+# and negative (before aniversary) af months, days and weeks.
+MEMBERSHIP_FEE_REMINDER_DATES = [
+    {'months': -3},  # 3 months before
+    {'months': -2},  # 2 months before
+    {'months': -1},  # 1 month before
+    {'days': 0},     # the day of anniversary
+    {'months': +1},  # 1 month after
+]
+
+# Customize template titles
+SITE_TITLE = "COIN - SI"
+SITE_HEADER = "COIN est un Outil pour un Internet Neutre"
+SITE_LOGO_URL = ''
+
 # Pattern used to display a unique reference for any subscription
 # Helpful for bank wire transfer identification
 SUBSCRIPTION_REFERENCE = 'REF-{subscription.offer.reference}-{subscription.pk}'
 
+# Template string to display the label the member should indicates for the bank
+# transfer
+MEMBERSHIP_REFERENCE = "ADH-{user.pk}"
+
 # Payment delay in days
 PAYMENT_DELAY = 30
 
@@ -270,6 +319,19 @@ FEEDS = (
 #    ('isp', 'http://isp.example.com/feed/', 3),
 )
 
+# Allow user to edit their VPS Info
+MEMBER_CAN_EDIT_VPS_CONF = True
+
+# Allow user to edit their VPN Info
+MEMBER_CAN_EDIT_VPN_CONF = True
+
+# Account registration
+# Allow visitor to join the association by register on COIN
+REGISTRATION_OPEN = False
+
+# All account with unvalidated email will be deleted after X days
+ACCOUNT_ACTIVATION_DAYS = 7
+
 # Member can edit their own data
 MEMBER_CAN_EDIT_PROFILE = False
 
@@ -278,3 +340,7 @@ HANDLE_BALANCE = False
 
 # Add subscription comments in invoice items
 INVOICES_INCLUDE_CONFIG_COMMENTS = True
+
+## maillist module
+# Command that push mailling-list subscribers to the lists server
+MAILLIST_SYNC_COMMAND = ''

+ 1 - 0
coin/settings_test.py

@@ -4,6 +4,7 @@ from settings_base import *
 
 EXTRA_INSTALLED_APPS = (
     'hardware_provisioning',
+    'maillists',
     'vpn',
 )
 

+ 18 - 0
coin/static/css/admin-local.css

@@ -0,0 +1,18 @@
+/* Remove the titles from inlines elements
+
+Generaly, this is redundant, with fields content */
+
+form .inline-group .inline-related td.original p, /* TabularInline */
+form .inline-group .inline-related h3 {           /* TabularStacked */
+    display: none;
+}
+.inline-group .tabular tr.has_original td {
+    padding-top: 5px;
+}
+
+/* Remove « Add » and « Edit » icons near member search in mailling list members management
+*/
+.inline-related.dynamic-maillinglistsubscription_set .related-widget-wrapper-link.change-related ,
+.inline-related.dynamic-maillinglistsubscription_set .related-widget-wrapper-link.add-related {
+    display: none;
+}

+ 53 - 13
coin/static/css/local.css

@@ -10,7 +10,7 @@ h1 {
     font-size: 2.2em;
     margin-bottom: 1em;
 }
-h1:before {
+h1 .default-logo:after {
     content: "\\_o<";
     color: #FF6600;
     font-weight: normal;
@@ -22,9 +22,10 @@ h1:before {
     width: 25%;
 }
 
-h1:hover:before {
+h1 .default-logo:hover:after {
     content: "\\_x<";
 }
+
 h1:hover:after {
     position: absolute;
     text-align: center;
@@ -38,6 +39,13 @@ h1 a, h1:after {
     font-weight: bold;
 }
 
+h1 span.columns {
+    /* avoid having different margins because of h1 font-size */
+    padding-left: 0.9375rem;
+    padding-right: 0.9375rem;
+}
+
+
 /* Barre de navigation */
 
 .side-nav {
@@ -173,6 +181,18 @@ table.no-background tr {
     word-break: break-all;
 }
 
+/* Specific table: mailling-list subscriptions */
+#mail-list-subscriptions .select-col {
+    min-width: 8rem;
+}
+#mail-list-subscriptions tr td select:last-child {
+    margin: 0;  /* So that they line-up vertically */
+    padding: 0;
+}
+#mail-list-subscriptions input[type=submit] {
+     min-width: 100%;
+}
+
 /* login page */
 #login-form {}
 #login-form table td {
@@ -198,20 +218,25 @@ table.no-background tr {
 /* Footer */
 
 #footer {
-    opacity: 0.18;
     margin-top: 20px;
 }
 #footer .line {
+    opacity: 0.18;
     widht:100%;
     border-bottom: 1px solid black;
 }
 #footer .duck {
+    opacity: 0.18;
     background-image: url('../img/coin.svg');
     background-size: auto 50%;
     background-repeat: no-repeat;
     background-position: center top;
     height:50px;
 }
+.licence-sentence {
+    opacity: 0.5;
+    text-align: center;
+}
 
 
 /* Invoices */
@@ -344,11 +369,11 @@ tr.inactive {
 }
 
 form .helptext {
-	position: relative;
-	top: -1em;
-	margin: 0em 1em 0em 1em;
-	font-style: italic;
-	font-size: small;
+    position: relative;
+    top: -1em;
+    margin: 0em 1em 0em 1em;
+    font-style: italic;
+    font-size: small;
 }
 
 /* Feeds */
@@ -391,24 +416,34 @@ form .helptext {
 }
 
 .message.success {
-	color: #FFFFFF;
-	background-color: #20BA44;
+    color: #FFFFFF;
+    background-color: #20BA44;
 }
 
 .message.warning {
-    color: #620
+    color: #620;
     background-color: #FFAE00;
     font-style: normal;
     border-radius: 0;
 }
 
+.message.error {
+    color: #B90202;
+    background-color: #FFBABA;
+}
+
+
 .eat-up {
-	margin-top: -1.5em;
+    margin-top: -1.5em;
 }
 .message.success:before {
     content: "✔ ";
 }
 
+.message.error:before {
+    content: "✘ ";
+}
+
 .nowrap {
     overflow: hidden;
     text-overflow: ellipsis;
@@ -418,5 +453,10 @@ form .helptext {
 /* List filters links */
 
 .list-filter {
-	text-align: right;
+    text-align: right;
+}
+
+/* Registration */
+.captcha {
+    display:none;
 }

+ 6 - 1
coin/templates/admin/base_site.html

@@ -1,15 +1,20 @@
 {% extends "admin/base.html" %}
 {% load i18n %}
 {% load staticfiles %}
+{% load hijack_tags %}
 
 {% block extrahead %}
+    <link rel="stylesheet" type="text/css" href="{% static 'hijack/hijack-styles.css' %}" />
+    <link rel="stylesheet" type="text/css" href="{% static 'css/admin-local.css' %}" />
     <script src="{% static "js/vendor/jquery.js" %}" type="text/javascript"></script>
+    <link rel="stylesheet" href="{% static "css/font-awesome.min.css"%}" />
     {% include 'autocomplete_light/static.html' %}
 {% endblock %}
 
-{% block title %}COIN ☺ Admin{% endblock %}
+{% block title %}Admin - COIN - {{ branding.shortname|capfirst }} SI{% endblock %}
 
 {% block branding %}
+{% hijack_notification %}
 <h1 id="site-name">Administration de COIN</h1>
 {% endblock %}
 

+ 15 - 2
coin/templates/base.html

@@ -1,20 +1,23 @@
 <!doctype html>
 {% load staticfiles %}
+{% load hijack_tags %}
 <html class="no-js" lang="en">
 <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-    <title>{% block title %}COIN - {{ branding.shortname|capfirst }} SI{% endblock %}</title>
+    <title>{% block title %}{{ SITE_TITLE }}{% endblock %}</title>
     <link rel="stylesheet" href="{% static "css/foundation.css"%}" />
     <link rel="stylesheet" href="{% static "css/font-awesome.min.css"%}" />
     <link rel="stylesheet" href="{% static "css/local.css" %}" />
     <link rel="stylesheet" href="{% static "css/offcanvas.css" %}">
+    <link rel="stylesheet" type="text/css" href="{% static 'hijack/hijack-styles.css' %}" />
     {% block extra_css %}{% endblock %}
     <script src="{% static "js/vendor/modernizr.js" %}"></script>
     <link rel="icon" type="image/png" href="{% static "img/coinitem.png" %}"/>
     <link rel="icon" type="image/x-icon" href="{% static "img/favicon.ico" %}" />
 </head>
 <body>
+{% hijack_notification %}
 <div class="off-canvas-wrap" data-offcanvas>
     <div class="inner-wrap">
 
@@ -31,7 +34,16 @@
             <div class="show-for-medium-up">
                 <div class="row">
                     <div class="large-12">
-                        <h1><a href="{% url 'home' %}">COIN est un Outil pour un Internet Neutre</a></h1>
+                        <h1>
+                            {% if SITE_LOGO_URL %}
+                            <span class="medium-3 large-3 columns">
+                                <img src="{{ SITE_LOGO_URL }}" alt="" />
+                            </span
+                            {% else %}
+                            <span class="default-logo">&nbsp;</span>
+                            {% endif %}
+                            <a href="{% url 'home' %}">{{ SITE_HEADER }}</a>
+                        </h1>
                     </div>
                 </div>
             </div>
@@ -78,6 +90,7 @@
                 <div class="small-2 columns"><div class="duck"></div></div>
                 <div class="small-5 columns"><div class="line">&nbsp;</div></div>
             </div>
+            <p class="licence-sentence">Site propulsé par <a href="https://code.ffdn.org/FFDN/coin">COIN</a> sous licence AGPLv3.</p>
             {% endblock %}
         </div>
 

+ 5 - 0
coin/templates/menu_items.html

@@ -7,6 +7,11 @@
 <li class="{% ifactive 'hardware_provisioning:loan-list' %}active{% endifactive %}"><a href="{% url 'hardware_provisioning:loan-list' %}"><i
             class="fa fa-exchange fa-fw"></i> Mon matériel</a></li>
 {% endif %}
+{% if 'maillists' in INSTALLED_APPS %}
+<li class="{% ifactive 'maillists:lists-list' %}active{% endifactive %}"><a href="{% url 'maillists:lists-list' %}"><i
+            class="fa fa-envelope fa-fw"></i> Listes mail</a></li>
+
+{% endif %}
 <li class="{% ifactive 'members:contact' %}active{% endifactive %}"><a href="{% url 'members:contact' %}"><i class="fa fa-life-ring fa-fw"></i> Contact / Support</a></li>
 <li class="divider"></li>
 {% if user.is_staff %}<li><a href="{% url 'admin:index' %}"><i class="fa fa-cogs fa-fw"></i> Administration</a></li>{% endif %}

+ 8 - 0
coin/urls.py

@@ -39,6 +39,7 @@ urlpatterns = patterns(
     url(r'^subscription/', include('coin.offers.urls', namespace='subscription')),
 
     url(r'^admin/', include(admin.site.urls)),
+    url(r'^hijack/', include('hijack.urls', namespace='hijack')),
 
     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 
@@ -53,3 +54,10 @@ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 
 # Pluggable apps URLs
 urlpatterns += list(apps_urlpatterns())
+
+
+if settings.DEBUG:
+    import debug_toolbar
+    urlpatterns = [
+        url(r'^__debug__/', include(debug_toolbar.urls)),
+    ] + urlpatterns

+ 3 - 0
coin/utils.py

@@ -118,6 +118,9 @@ delete_selected.short_description = "Supprimer tous les objets sélectionnés."
 def in_one_year():
     return date.today() + timedelta(365)
 
+def one_year_ago():
+    return date.today() - timedelta(365)
+
 
 def start_of_month():
     return date(date.today().year, date.today().month, 1)

+ 3 - 4
coin/views.py

@@ -6,7 +6,7 @@ import HTMLParser
 
 from django.views.decorators.cache import cache_page
 from django.template import RequestContext
-from django.shortcuts import render_to_response
+from django.shortcuts import render
 from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError
 from django.conf import settings
 
@@ -36,8 +36,7 @@ def feed(request, feed_name):
         feed = feedparser.parse(feed_url)
         entries = feed.entries[:limit]
 
-        return render_to_response('fragments/feed.html',
-                                  {'feed_entries': entries},
-                                  context_instance=RequestContext(request))
+        return render(request, 'fragments/feed.html',
+                                  {'feed_entries': entries})
     except:
         return HttpResponseServerError('')

+ 1 - 1
contrib/ansible/coin-customizations/django_local_settings.py.j2

@@ -27,7 +27,7 @@ STATIC_ROOT = '{{ www_static_assets_directory }}'
 #EMAIL_USE_TLS = True
 #EMAIL_HOST = "localhost"
 
-MEMBER_DEFAULT_COTISATION = 16
+DEFAULT_MEMBERSHIP_FEE = 16
 
 FEEDS = (
           #('isp', 'https://faimaison.net/feeds/all.atom.xml', 3),

BIN
doc/_img/admin-maillists.png


BIN
doc/_img/user-maillists.png


BIN
doc/_img/user-subscriptions.png


+ 125 - 0
doc/admin/maillists.md

@@ -0,0 +1,125 @@
+Gestion des abonnements aux listes mail
+=======================================
+
+Coin offre un module optionnel pour que les adhérent·e·s puissent
+s'abonner/désabonner aux listes mail de l'asso. de manière autonome (listes de
+discussions et/ou de diffusion).
+
+Coin n'est pas lui-même un serveur de listes mail. Il se contente de
+s'interfacer avec ce dernier pour lui pousser des liste d'inscrit·e·s.
+
+Il existe une interface membre pour auto-gérer ses propres abonnements, et une
+interface admin pour gérer l'ensemble des abonnements lorsqu'on possède les
+droits admin dans coin.
+
+![vue adhérent](../_img/user-maillists.png)
+![vue admin](../_img/admin-maillists.png)
+
+Vues adhérent·e et admin
+
+
+Fonctionnement
+--------------
+
+Coin stocke les abonnements des membres aux listes dans sa base de données, en
+utilisant l'adresse mail de la fiche membre.
+
+Il synchronise ensuite ces listes vers le serveur de listes mail en appelant
+une commande pour chaque liste gérée. Cette commande est configurable, et
+reçoit sur son entrée standard la liste des emails inscrits (une adresse mail
+par ligne).
+
+Si le serveur de base données est sur une machine différente du serveur Coin,
+il est possible d'utiliser la commande SSH qui appelle un script distant.
+
+
+La synchronisation sera faite :
+
+- À l'abonnement/désabonnement à une liste via l'interface admin de Coin
+  (section « Listes mail ») ;
+- à l'abonnement/désabonnement à une liste via l'interface membre de Coin ;
+- au changement d'adresse mail d'un·e adhérent·e ;
+- à la suppression d'un·e adhérent·e.
+
+Avertissements
+---------------
+
+- En l'état, tout membre avec des identifiants Coin aura pouvoir d'auto-gérer
+son inscription à toute liste gérée par coin. Il n'est cependant pas
+obligatoire donner à Coin la main sur les abonnements à toutes les listes d'un
+serveur de listes.
+
+- Il est préférable que les listes mail gérées par Coin le soient totalement. Si
+des inscriptions sont faites par d'autres moyens (mail, interface du serveur de
+liste de discussions… etc), ces modifications risquent d'être écrasées par la
+gestion d'abonnements de Coin.
+
+- La commande de synchro est lancée à chaque abonnement/désabonnement. Il y a
+  un outil d'import « en masse » : [import_mailling_list](#méthode-b-importer-des-abonnements-en-masse).
+
+Mise en place
+-------------
+
+
+### 1. Activer l'app *maillist*
+
+Il faut activer l'app *maillists*, cela
+fonctionne
+[comme les autres apps optionelles](../README.md#using-optional-apps). Il faut
+ensuite lancer la commande suivante pour mettre à jour la base de données :
+
+    ./manage.py migrate
+
+
+### 2. Configurer la synchronisation.
+
+
+Il y a un paramètre obligatoire à renseigner dans votre fichier.
+*settings_local.py* : `MAILLIST_SYNC_COMMAND`.
+
+Il s'agit de la commande à lancer pour « pousser » la liste d'emails inscrits à
+une liste mail donnée. 
+
+Vous pouvez utiliser des variables dans la commande à
+lancer :
+
+- `{short_name}` : l'identifiant court de la liste (ex: *discussion*)
+- `{email}` : l'email de la liste (ex: *discussion@example.com*)
+
+Si par exemple votre serveur de listes attend un bête fichier texte
+avec une adresse par ligne dans */etc/lists/nomdelaliste* :
+
+
+    MAILLIST_SYNC_COMMAND = 'tee /etc/lists/{short_name}'
+    
+Si le ce même serveur se situe sur un autre serveur, on pourra utiliser par
+exemple :
+
+    MAILLIST_SYNC_COMMAND = "ssh coin@mail.example.com 'tee /etc/lists/{short_name}'"
+
+Des cas d'usages plus complexes (ex: inscription via une API HTTP) sont
+envisageables en recourant à un petit script sur mesure.
+
+
+### 3. Ajouter des listes
+
+Deux méthodes, selon que vous voulez initialiser la liste avec une vide ou
+pré-remplie avec une liste d'abonnés.
+
+#### Méthode A : créer une liste vide
+
+Se rendre dans l'admin de coin et dans la nouvelle catégorie « Listes mail »,
+renseigner les listes mail que l'on souhaite voir gérées par Coin.
+
+#### Méthode B : importer des abonnements « en masse »
+
+Pour créer une liste et faire un import initial de tou·te·s ses abonné·e·s d'un
+coup, vous pouvez utiliser la commande `./manage.py import_mailling_list` qui
+permet de créer une liste à partir de son adresse, son nom et d'un fichier
+texte contenant les adresses à abonner (qui doivent correspondre à des membres
+renseignés dans coin).
+
+Pour plus d'infos : `./manage.py import_mailling_list --help`
+
+*NB : Il vous faudra ensuite aller renseigner, via l'interface d'admin de coin,
+la description complète de la liste (celle que verront les membres).*

+ 25 - 0
hardware_provisioning/migrations/0018_auto_20180819_0211.py

@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+from django.conf import settings
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('hardware_provisioning', '0017_item_deployed'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='item',
+            options={'ordering': ['designation', 'mac_address', 'serial'], 'verbose_name': 'objet'},
+        ),
+        migrations.AlterField(
+            model_name='loan',
+            name='user',
+            field=models.ForeignKey(related_name='loans', on_delete=django.db.models.deletion.SET_NULL, verbose_name='membre', to=settings.AUTH_USER_MODEL, null=True),
+        ),
+    ]

+ 3 - 2
hardware_provisioning/models.py

@@ -144,8 +144,9 @@ class LoanQuerySet(models.QuerySet):
 
 class Loan(models.Model):
     item = models.ForeignKey(Item, verbose_name='objet', related_name='loans')
-    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='membre',
-                             related_name='loans')
+    user = models.ForeignKey(
+        settings.AUTH_USER_MODEL, verbose_name='membre',
+        related_name='loans', null=True, on_delete=models.SET_NULL)
     loan_date = models.DateTimeField(verbose_name='date de prêt')
     loan_date_end = models.DateTimeField(verbose_name='date de fin de prêt',
                                      null=True, blank=True)

+ 3 - 1
hardware_provisioning/templates/hardware_provisioning/item_borrow.html

@@ -1,5 +1,7 @@
 {% extends 'hardware_provisioning/base.html' %}
 
+{% block title %}Confirmation d'emprunt - {{ block.super }}{% endblock %}
+
 {% block content %}
 
 <p>Je déclare emprunter le matériel <strong>{{item }} ({{ item.type }}</strong>) à compter de ce jour.</p>
@@ -11,4 +13,4 @@
            value="Oui oui, c'est bien ça."/>
 </form>
 
-{% endblock %}
+{% endblock %}

+ 2 - 1
hardware_provisioning/templates/hardware_provisioning/item_list.html

@@ -1,5 +1,6 @@
 {% extends "hardware_provisioning/base.html" %}
 
+{% block title %}Emprunt d'objet - {{ block.super }}{% endblock %}
 {% block content %}
 <h2>J'emprunte à l'association…</h2>
 
@@ -35,4 +36,4 @@
     </tbody>
 
 </table>
-{% endblock %}
+{% endblock %}

+ 2 - 0
hardware_provisioning/templates/hardware_provisioning/list.html

@@ -1,5 +1,7 @@
 {% extends "hardware_provisioning/base.html" %}
 
+{% block title %}Mon matériel - {{ block.super }}{% endblock %}
+
 {% block content %}
 {% if view  == 'old' %}
 <h2>L'association m'a prêté…</h2>

+ 3 - 1
hardware_provisioning/templates/hardware_provisioning/return.html

@@ -1,5 +1,7 @@
 {% extends "hardware_provisioning/base.html" %}
 
+{% block title %}Retour de matériel - {{ block.super }}{% endblock %}
+
 {% block content %}
 <h2>Retour de matériel</h2>
 <p>
@@ -10,4 +12,4 @@
   <input class="success button" type="submit"
          value="Oui oui, c'est bien ça."/>
 </form>
-{% endblock %}
+{% endblock %}

+ 3 - 1
hardware_provisioning/templates/hardware_provisioning/transfer.html

@@ -1,5 +1,7 @@
 {% extends "hardware_provisioning/base.html" %}
 
+{% block title %}Transfert de matériel - {{ block.super }}{% endblock %}
+
 {% block content %}
 <h2>Transfert de matériel</h2>
 <p>
@@ -15,4 +17,4 @@
   <input class="success button" type="submit"
          value="Oui oui, c'est bien ça."/>
 </form>
-{% endblock %}
+{% endblock %}

+ 1 - 0
housing/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'housing.apps.HousingConfig'

+ 84 - 0
housing/admin.py

@@ -0,0 +1,84 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.contrib import admin
+from polymorphic.admin import PolymorphicChildModelAdmin
+
+from coin.configuration.admin import ConfigurationAdminFormMixin
+from coin.utils import delete_selected
+
+from .models import HousingConfiguration
+
+
+
+class HousingConfigurationInline(admin.StackedInline):
+    model = HousingConfiguration
+    # fk_name = 'offersubscription'
+    readonly_fields = ['configuration_ptr']
+
+
+class HousingConfigurationAdmin(ConfigurationAdminFormMixin, PolymorphicChildModelAdmin):
+    base_model = HousingConfiguration
+    list_display = ('offersubscription', 'activated',
+                    'ipv4_endpoint', 'ipv6_endpoint', 'comment')
+    list_filter = ('activated',)
+    search_fields = ('comment',
+                     # TODO: searching on member directly doesn't work
+                     'offersubscription__member__first_name',
+                     'offersubscription__member__last_name',
+                     'offersubscription__member__email')
+    actions = (delete_selected, "generate_endpoints", "generate_endpoints_v4",
+               "generate_endpoints_v6", "activate", "deactivate")
+    inline = HousingConfigurationInline
+
+    def get_readonly_fields(self, request, obj=None):
+        if obj:
+            return []
+        else:
+            return []
+
+    def set_activation(self, request, queryset, value):
+        count = 0
+        # We must update each object individually, because we want to run
+        # the save() method to update the backend.
+        for housing in queryset:
+            if housing.activated != value:
+                housing.activated = value
+                housing.full_clean()
+                housing.save()
+                count += 1
+        action = "activated" if value else "deactivated"
+        msg = "{} Housing subscription(s) {}.".format(count, action)
+        self.message_user(request, msg)
+
+    def activate(self, request, queryset):
+        self.set_activation(request, queryset, True)
+    activate.short_description = "Activate selected Housings"
+
+    def deactivate(self, request, queryset):
+        self.set_activation(request, queryset, False)
+    deactivate.short_description = "Deactivate selected Housings"
+
+    def generate_endpoints_generic(self, request, queryset, v4=True, v6=True):
+        count = 0
+        for housing in queryset:
+            if housing.generate_endpoints(v4, v6):
+                housing.full_clean()
+                housing.save()
+                count += 1
+        msg = "{} Housing subscription(s) updated.".format(count)
+        self.message_user(request, msg)
+
+    def generate_endpoints(self, request, queryset):
+        self.generate_endpoints_generic(request, queryset)
+    generate_endpoints.short_description = "Generate IPv4 and IPv6 endpoints"
+
+    def generate_endpoints_v4(self, request, queryset):
+        self.generate_endpoints_generic(request, queryset, v6=False)
+    generate_endpoints_v4.short_description = "Generate IPv4 endpoints"
+
+    def generate_endpoints_v6(self, request, queryset):
+        self.generate_endpoints_generic(request, queryset, v4=False)
+    generate_endpoints_v6.short_description = "Generate IPv6 endpoints"
+
+admin.site.register(HousingConfiguration, HousingConfigurationAdmin)

+ 14 - 0
housing/apps.py

@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+import coin.apps
+
+from . import urls
+
+
+class HousingConfig(AppConfig, coin.apps.AppURLs):
+    name = 'housing'
+    verbose_name = "Gestion d'accès Housing"
+
+    exported_urlpatterns = [('housing', urls.urlpatterns)]

+ 30 - 0
housing/migrations/0001_initial.py

@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import netfields.fields
+import coin.validation
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('configuration', '0004_auto_20161015_1837'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='HousingConfiguration',
+            fields=[
+                ('configuration_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='configuration.Configuration')),
+                ('activated', models.BooleanField(default=False, verbose_name='activ\xe9')),
+                ('ipv4_endpoint', netfields.fields.InetAddressField(validators=[coin.validation.validate_v4], max_length=39, blank=True, help_text='Adresse IPv4 utilis\xe9e par d\xe9faut sur le Housing', null=True, verbose_name='IPv4')),
+                ('ipv6_endpoint', netfields.fields.InetAddressField(validators=[coin.validation.validate_v6], max_length=39, blank=True, help_text='Adresse IPv6 utilis\xe9e par d\xe9faut sur le Housing', null=True, verbose_name='IPv6')),
+                ('vlan', models.IntegerField(null=True, verbose_name='vlan id')),
+            ],
+            options={
+                'verbose_name': 'Housing',
+            },
+            bases=('configuration.configuration',),
+        ),
+    ]

+ 0 - 0
housing/migrations/__init__.py


+ 111 - 0
housing/models.py

@@ -0,0 +1,111 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models
+from polymorphic import PolymorphicModel
+from django.core.exceptions import ValidationError
+from django.core.urlresolvers import reverse
+from netfields import InetAddressField, NetManager
+
+from coin.configuration.models import Configuration
+# from coin.offers.backends import ValidateBackendType
+from coin import validation
+
+"""BIG FAT WARNING
+
+Ce code requiert une sévère factorisation avec vpn/models.py et vps/models.py
+
+"""
+
+
+class HousingConfiguration(Configuration):
+    url_namespace = "housing"
+    activated = models.BooleanField(default=False, verbose_name='activé')
+    ipv4_endpoint = InetAddressField(validators=[validation.validate_v4],
+                                     verbose_name="IPv4", blank=True, null=True,
+                                     help_text="Adresse IPv4 utilisée par "
+                                     "défaut sur le Housing")
+    ipv6_endpoint = InetAddressField(validators=[validation.validate_v6],
+                                     verbose_name="IPv6", blank=True, null=True,
+                                     help_text="Adresse IPv6 utilisée par "
+                                     "défaut sur le Housing")
+    vlan = models.IntegerField(verbose_name="vlan id", null=True)
+    objects = NetManager()
+
+    def get_absolute_url(self):
+        return reverse('housing:details', args=[str(self.pk)])
+
+    # This method is part of the general configuration interface.
+    def subnet_event(self):
+        self.check_endpoints(delete=True)
+        # We potentially changed the endpoints, so we need to save.  Also,
+        # saving will update the subnets in the LDAP backend.
+        self.full_clean()
+        self.save()
+
+    def get_subnets(self, version):
+        subnets = self.ip_subnet.all()
+        return [subnet for subnet in subnets if subnet.inet.version == version]
+
+    def generate_endpoints(self, v4=True, v6=True):
+        """Generate IP endpoints in one of the attributed IP subnets.  If there is
+        no available subnet for a given address family, then no endpoint
+        is generated for this address family.  If there already is an
+        endpoint, do nothing.
+
+        Returns True if an endpoint was generated.
+
+        TODO: this should be factored for other technologies (DSL, etc)
+
+        """
+        subnets = self.ip_subnet.all()
+        updated = False
+        if v4 and self.ipv4_endpoint is None:
+            subnets_v4 = [s for s in subnets if s.inet.version == 4]
+            if len(subnets_v4) > 0:
+                self.ipv4_endpoint = subnets_v4[0].inet.ip
+                updated = True
+        if v6 and self.ipv6_endpoint is None:
+            subnets_v6 = [s for s in subnets if s.inet.version == 6]
+            if len(subnets_v6) > 0:
+                # With v6, we choose the second host of the subnet (cafe::1)
+                gen = subnets_v6[0].inet.iter_hosts()
+                gen.next()
+                self.ipv6_endpoint = gen.next()
+                updated = True
+        return updated
+
+    def check_endpoints(self, delete=False):
+        """Check that the IP endpoints are included in one of the attributed IP
+        subnets.
+
+        If [delete] is True, then simply delete the faulty endpoints
+        instead of raising an exception.
+        """
+        error = "L'IP {} n'est pas dans un réseau attribué."
+        subnets = self.ip_subnet.all()
+        is_faulty = lambda endpoint : endpoint and not any([endpoint in subnet.inet for subnet in subnets])
+        if is_faulty(self.ipv4_endpoint):
+            if delete:
+                self.ipv4_endpoint = None
+            else:
+                raise ValidationError(error.format(self.ipv4_endpoint))
+        if is_faulty(self.ipv6_endpoint):
+            if delete:
+                self.ipv6_endpoint = None
+            else:
+                raise ValidationError(error.format(self.ipv6_endpoint))
+
+    def clean(self):
+        # If saving for the first time and IP endpoints are not specified,
+        # generate them automatically.
+        if self.pk is None:
+            self.generate_endpoints()
+        self.check_endpoints()
+
+    def __unicode__(self):
+        return 'Housing ' #+ self.login
+
+    class Meta:
+        verbose_name = 'Housing'
+

+ 40 - 0
housing/templates/housing/housing.html

@@ -0,0 +1,40 @@
+{% extends "base.html" %}
+
+{% load subnets %}
+
+{% block content %}
+<div class="row">
+    <h2>Configuration du Housing</h2>
+    {% for message in messages %}
+        <div class="message eat-up{% if message.tags %} {{ message.tags }}{% endif %}">
+            {{ message }}
+        </div>
+    {% endfor %}
+    <div class="large-12 columns">
+        <div class="panel">
+            <h3>Adresses IP</h3>
+            <table class="full-width">
+                <tr class="flatfield">
+                    <td class="center"><span class="label">VLAN ID</span></td>
+                    <td>{{ object.vlan }}</td>
+                </tr>
+                <tr class="flatfield">
+                    <td class="center"><span class="label">IPv4</span></td>
+                    <td>{{ object.ipv4_endpoint }}</td>
+                </tr>
+                <tr class="flatfield">
+                    <td class="center"><span class="label">IPv6</span></td>
+                    <td>{{ object.ipv6_endpoint }}</td>
+                </tr>
+                <tr>
+                    <td class="center"><span class="label">Sous-réseaux</span></td>
+                    <td>
+                        {% for subnet in object.ip_subnet.all %}{{ subnet|prettify }}<br/>{% endfor %}
+                    </td>
+                </tr>
+            </table>
+        </div>
+    </div>
+</div>
+
+{% endblock %}

+ 124 - 0
housing/tests.py

@@ -0,0 +1,124 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from unittest import skipUnless
+
+from django.test import TestCase
+from django.conf import settings
+
+from coin.offers.models import Offer, OfferSubscription
+from coin.resources.models import IPPool, IPSubnet
+from coin.members.models import Member
+from coin.members.tests import MemberTestsUtils
+
+from .models import HousingConfiguration
+
+USING_POSTGRES = (settings.DATABASES['default']['ENGINE']
+                  ==
+                  'django.db.backends.postgresql_psycopg2')
+
+
+""" BIG FAT WARNING
+
+Ce code requiert une sévère factorisation avec vpn/tests.py et vps/tests.py
+
+"""
+
+
+class HousingTestCase(TestCase):
+    fixtures = ['example_pools.json', 'offers.json']
+
+    def setUp(self):
+        self.v6_pool = IPPool.objects.get(default_subnetsize=56)
+        self.v4_pool = IPPool.objects.get(default_subnetsize=32)
+        self.offer = Offer.objects.filter(configuration_type="HousingConfiguration")[0]
+
+        # Create a member.
+        cn = MemberTestsUtils.get_random_username()
+        self.member = Member.objects.create(first_name=u"Toto",
+                                            last_name=u"L'artichaut",
+                                            username=cn)
+
+        # Create a new Housing with subnets.
+        # We need Django to call clean() so that magic happens.
+        abo = OfferSubscription(offer=self.offer, member=self.member)
+        abo.full_clean()
+        abo.save()
+        housing = HousingConfiguration(offersubscription=abo)
+        housing.full_clean()
+        housing.save()
+        v6 = IPSubnet(ip_pool=self.v6_pool, configuration=housing)
+        v6.full_clean()
+        v6.save()
+        v4 = IPSubnet(ip_pool=self.v4_pool, configuration=housing)
+        v4.full_clean()
+        v4.save()
+
+        # Create additional Housing, they should automatically be attributed a
+        # new login.
+        for i in range(5):
+            abo = OfferSubscription(offer=self.offer, member=self.member)
+            abo.full_clean()
+            abo.save()
+            housing = HousingConfiguration(offersubscription=abo)
+            housing.full_clean()
+            housing.save()
+
+    def tearDown(self):
+        """Properly clean up objects, so that they don't stay in LDAP"""
+        for housing in HousingConfiguration.objects.all():
+            housing.delete()
+        Member.objects.get().delete()
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_has_ipv4_endpoint(self):
+        housing = HousingConfiguration.objects.all()[0]
+        self.assertIsNotNone(housing.ipv4_endpoint)
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_has_correct_ipv4_endpoint(self):
+        """If there is not endpoint, we consider it to be correct."""
+        housing = HousingConfiguration.objects.all()[0]
+        if housing.ipv4_endpoint is not None:
+            subnet = housing.ip_subnet.get(ip_pool=self.v4_pool)
+            self.assertIn(housing.ipv4_endpoint, subnet.inet)
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_has_ipv6_endpoint(self):
+        housing = HousingConfiguration.objects.all()[0]
+        self.assertIsNotNone(housing.ipv6_endpoint)
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_has_correct_ipv6_endpoint(self):
+        """If there is not endpoint, we consider it to be correct."""
+        housing = HousingConfiguration.objects.all()[0]
+        if housing.ipv6_endpoint is not None:
+            subnet = housing.ip_subnet.get(ip_pool=self.v6_pool)
+            self.assertIn(housing.ipv6_endpoint, subnet.inet)
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_change_v4subnet_is_housing_endpoint_correct(self):
+        housing = HousingConfiguration.objects.all()[0]
+        subnet = housing.ip_subnet.get(ip_pool=self.v4_pool)
+        subnet.inet = "192.168.42.42/31"
+        subnet.full_clean()
+        subnet.save()
+        self.test_has_correct_ipv4_endpoint()
+
+    @skipUnless(USING_POSTGRES, "Using a postgresql-only field")
+    def test_change_v6subnet_is_housing_endpoint_correct(self):
+        housing = HousingConfiguration.objects.all()[0]
+        subnet = housing.ip_subnet.get(ip_pool=self.v6_pool)
+        subnet.inet = "2001:db8:4242:4200::/56"
+        subnet.full_clean()
+        subnet.save()
+        self.test_has_correct_ipv6_endpoint()
+
+    def test_automatic_login(self):
+        housing = HousingConfiguration.objects.all()[0]
+        expected_login = housing.offersubscription.member.username + "-housing1"
+        self.assertEqual(housing.login, expected_login)
+
+    def test_has_multiple_housing(self):
+        housings = HousingConfiguration.objects.all()
+        self.assertEqual(len(housings), 6)

+ 13 - 0
housing/urls.py

@@ -0,0 +1,13 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.conf.urls import patterns, url
+
+from .views import HousingView
+
+urlpatterns = patterns(
+    '',
+    # This is part of the generic configuration interface (the "name" is
+    # the same as the "backend_name" of the model).
+    url(r'^(?P<pk>\d+)$', HousingView.as_view(template_name="housing/housing.html"), name="details"),
+)

+ 34 - 0
housing/views.py

@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.shortcuts import get_object_or_404
+from django.views.generic.edit import UpdateView
+from django.conf import settings
+from django.contrib.messages.views import SuccessMessageMixin
+from django.contrib.auth.decorators import login_required
+from django.utils.decorators import method_decorator
+
+from coin.members.models import Member
+
+from .models import HousingConfiguration
+
+
+class HousingView(SuccessMessageMixin, UpdateView):
+    model = HousingConfiguration
+    fields = ['ipv4_endpoint', 'ipv6_endpoint', 'comment']
+    success_message = "Configuration enregistrée avec succès !"
+
+    @method_decorator(login_required)
+    def dispatch(self, *args, **kwargs):
+        return super(HousingView, self).dispatch(*args, **kwargs)
+
+    def get_form(self, form_class=None):
+        return None
+
+    def get_object(self):
+        if self.request.user.is_superuser:
+            return get_object_or_404(HousingConfiguration, pk=self.kwargs.get("pk"))
+        # For normal users, ensure the Housing belongs to them.
+        return get_object_or_404(HousingConfiguration, pk=self.kwargs.get("pk"),
+                                 offersubscription__member=self.request.user)
+

+ 1 - 0
maillists/__init__.py

@@ -0,0 +1 @@
+default_app_config = 'maillists.app.MailListsConfig'

+ 118 - 0
maillists/admin.py

@@ -0,0 +1,118 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
+
+import autocomplete_light
+from django.contrib import admin
+from django.contrib import messages
+from django.http import HttpResponseRedirect
+
+from .models import MaillingList, MaillingListSubscription, SyncCommandError
+import coin.members.admin
+
+
+class AddMaillingListSubscriptionInline(admin.StackedInline):
+    model = MaillingListSubscription
+    extra = 0
+    fields = ('member', 'maillinglist')
+    verbose_name_plural = "Ajouter un abonnement à une liste mail"
+    verbose_name = "abonnement"
+
+    form = autocomplete_light.modelform_factory(MaillingListSubscription, fields='__all__')
+
+    def get_queryset(self, request):
+        qs = super(AddMaillingListSubscriptionInline, self).get_queryset(request)
+        return qs.none()
+
+    def has_delete_permission(self, request, obj=None):
+        return False
+
+
+class AddSubscriberInline(AddMaillingListSubscriptionInline):
+    verbose_name_plural = "Ajouter des abonné·e·s"
+    verbose_name = "abonné·e"
+
+
+class MaillingListSubscriptionInline(admin.TabularInline):
+    model = MaillingListSubscription
+
+    readonly_fields = ('member', 'maillinglist',)
+
+    def has_add_permission(self, request, obj=None):
+        return False
+
+
+class SubscribersInline(MaillingListSubscriptionInline):
+    fields = ('member', 'email', 'maillinglist',)
+    readonly_fields = ('member', 'email', 'maillinglist',)
+    verbose_name_plural = "Abonné·e·s"
+    verbose_name = "abonné·e"
+
+    def email(self, instance):
+        return instance.member.email
+
+
+class MaillingListAdmin(admin.ModelAdmin):
+    list_display = ('email', 'verbose_name')
+    actions = ['sync_to_server']
+
+    def sync_to_server(self, request, queryset):
+        for _list in queryset.all():
+            try:
+                _list.sync_to_list_server()
+            except Exception as e:
+                messages.error(
+                    request,
+                    'Impossible de synchroniser la liste {} : "{}"'.format(
+                        _list, e))
+            else:
+                messages.success(
+                    request,
+                    'Liste {} synchronisée vers le serveur'.format(
+                        _list.email))
+    sync_to_server.short_description = (
+        'Synchroniser les listes sélectionnées vers le serveur')
+
+    inlines = [AddSubscriberInline, SubscribersInline]
+
+    def change_view(self, request, object_id, *args, **kwargs):
+        try:
+            return super(MaillingListAdmin, self).change_view(
+                request, object_id, *args, **kwargs)
+        except SyncCommandError as e:
+            try:
+                ml = MaillingList.objects.get(pk=object_id)
+                ml_name = "La liste mail « {} »".format(ml.short_name)
+            except MaillingList.DoesNotExist:
+                ml_name = "La nouvelle liste mail"
+            messages.error(
+                request,
+                "{} n'a pas pu être synchronisée".format(ml_name) +
+                " vers le serveur de listes : « {} ».".format(e))
+            return HttpResponseRedirect(request.path)
+
+
+admin.site.register(MaillingList, MaillingListAdmin)
+
+
+class MemberAdmin(coin.members.admin.MemberAdmin):
+    inlines = coin.members.admin.MemberAdmin.inlines + [
+        MaillingListSubscriptionInline,
+        AddMaillingListSubscriptionInline,
+    ]
+
+    def change_view(self, request, *args, **kwargs):
+        try:
+            return super(MemberAdmin, self).change_view(
+                request, *args, **kwargs)
+        except SyncCommandError as e:
+            messages.error(
+                request,
+                "Les listes mails n'ont pas pu être synchronisées" +
+                " vers le serveur de listes : « {} ».".format(e))
+            return HttpResponseRedirect(request.path)
+
+
+admin.site.unregister(coin.members.admin.Member)
+admin.site.register(coin.members.admin.Member, MemberAdmin)

+ 0 - 0
maillists/app.py


Some files were not shown because too many files changed in this diff