Files @ 8e197f347fed
Branch filter:

Location: rattail-project/rattail/rattail/db/model/customers.py

lance
Add `PendingCustomer` model, for sake of new custorder workflow
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# -*- coding: utf-8; -*-
################################################################################
#
#  Rattail -- Retail Software Framework
#  Copyright © 2010-2021 Lance Edgar
#
#  This file is part of Rattail.
#
#  Rattail is free software: you can redistribute it and/or modify it under the
#  terms of the GNU General Public License as published by the Free Software
#  Foundation, either version 3 of the License, or (at your option) any later
#  version.
#
#  Rattail 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 General Public License for more
#  details.
#
#  You should have received a copy of the GNU General Public License along with
#  Rattail.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Data Models for Customers
"""

from __future__ import unicode_literals, absolute_import

import datetime

import six
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.orderinglist import ordering_list

from rattail.db.model import (Base, uuid_column, getset_factory,
                              PhoneNumber, EmailAddress, MailingAddress,
                              Person, Note, User)
from .contact import ContactMixin


class Customer(ContactMixin, Base):
    """
    Represents a customer account.

    Customer accounts may consist of more than one person, in some cases.
    """
    __tablename__ = 'customer'
    __versioned__ = {}

    uuid = uuid_column()

    id = sa.Column(sa.String(length=20), nullable=True, doc="""
    String ID for the customer, if known/relevant.  This may or may not
    correspond to the :attr:`number`, depending on your system.
    """)

    number = sa.Column(sa.Integer(), nullable=True, doc="""
    Customer number, if known/relevant.  This may or may not correspond to the
    :attr:`id`, depending on your system.
    """)

    name = sa.Column(sa.String(length=255))
    email_preference = sa.Column(sa.Integer())

    wholesale = sa.Column(sa.Boolean(), nullable=True, doc="""
    Flag indicating whether the customer is a "wholesale" account - whatever
    that happens to mean for your business logic.
    """)

    active_in_pos = sa.Column(sa.Boolean(), nullable=True, doc="""
    Whether or not the customer account should be "active" within the POS
    system, if applicable.  Whether/how this field is populated and/or
    leveraged are up to your system.
    """)

    active_in_pos_sticky = sa.Column(sa.Boolean(), nullable=False, default=False, doc="""
    Whether or not the customer account should *always* be "active" within the
    POS system.  This field may be useful if :attr:`active_in_pos` gets set
    dynamically.
    """)

    invalid_address = sa.Column(sa.Boolean(), nullable=True, doc="""
    Flag indicating the customer's mailing address(es) on file are invalid.
    """)

    def __str__(self):
        if six.PY2:
            return unicode(self).encode('utf8')
        return self.name or ""

    if six.PY2:
        def __unicode__(self):
            return self.name or ""

    def add_email_address(self, address, type='Home'):
        email = CustomerEmailAddress(address=address, type=type)
        self.emails.append(email)
        return email

    def add_phone_number(self, number, type='Home'):
        phone = CustomerPhoneNumber(number=number, type=type)
        self.phones.append(phone)
        return phone

    def add_mailing_address(self, **kwargs):
        addr = CustomerMailingAddress(**kwargs)
        self.addresses.append(addr)
        return addr

    @property
    def employee(self):
        """
        Return the employee associated with the customer, if any.  Assumes a
        certain "typical" relationship path.
        """
        if self.person:
            return self.person.employee

    def first_person(self):
        """
        Convenience method to retrieve the "first" Person record which is
        associated with this customer, or ``None``.
        """
        if self.people:
            return self.people[0]

    def only_person(self, require=True):
        """
        Convenience method to retrieve the one and only Person record which is
        associated with this customer.  An error will be raised if there is not
        exactly one person associated.
        """
        if len(self.people) > 1 or (require and not self.people):
            raise ValueError("customer {} should have 1 person but instead has {}: {}".format(
                self.uuid, len(self.people), self))
        return self.people[0] if self.people else None

    def only_member(self, require=True):
        """
        Convenience method to retrieve the one and only Member record which is
        associated with this customer.  If ``require=True`` then an error will
        be raised if there is not exactly one member found.
        """
        if len(self.members) > 1 or (require and not self.members):
            raise ValueError("customer {} should have 1 member but instead has {}: {}".format(
                self.uuid, len(self.members), self))
        return self.members[0] if self.members else None


class CustomerPhoneNumber(PhoneNumber):
    """
    Represents a phone (or fax) number associated with a :class:`Customer`.
    """

    __mapper_args__ = {'polymorphic_identity': 'Customer'}


Customer._contact_phone_model = CustomerPhoneNumber

Customer.phones = orm.relationship(
    CustomerPhoneNumber,
    backref='customer',
    primaryjoin=CustomerPhoneNumber.parent_uuid == Customer.uuid,
    foreign_keys=[CustomerPhoneNumber.parent_uuid],
    collection_class=ordering_list('preference', count_from=1),
    order_by=CustomerPhoneNumber.preference,
    cascade='save-update, merge, delete, delete-orphan')

Customer.phone = orm.relationship(
    CustomerPhoneNumber,
    primaryjoin=sa.and_(
        CustomerPhoneNumber.parent_uuid == Customer.uuid,
        CustomerPhoneNumber.preference == 1),
    foreign_keys=[CustomerPhoneNumber.parent_uuid],
    uselist=False,
    viewonly=True)


class CustomerEmailAddress(EmailAddress):
    """
    Represents an email address associated with a :class:`Customer`.
    """

    __mapper_args__ = {'polymorphic_identity': 'Customer'}


Customer._contact_email_model = CustomerEmailAddress

Customer.emails = orm.relationship(
    CustomerEmailAddress,
    backref='customer',
    primaryjoin=CustomerEmailAddress.parent_uuid == Customer.uuid,
    foreign_keys=[CustomerEmailAddress.parent_uuid],
    collection_class=ordering_list('preference', count_from=1),
    order_by=CustomerEmailAddress.preference,
    cascade='save-update, merge, delete, delete-orphan')

Customer.email = orm.relationship(
    CustomerEmailAddress,
    primaryjoin=sa.and_(
        CustomerEmailAddress.parent_uuid == Customer.uuid,
        CustomerEmailAddress.preference == 1),
    foreign_keys=[CustomerEmailAddress.parent_uuid],
    uselist=False,
    viewonly=True)


class CustomerMailingAddress(MailingAddress):
    """
    Represents a mailing address for a customer
    """
    __mapper_args__ = {'polymorphic_identity': 'Customer'}


Customer._contact_address_model = CustomerMailingAddress

Customer.addresses = orm.relationship(
    CustomerMailingAddress,
    backref='customer',
    primaryjoin=CustomerMailingAddress.parent_uuid == Customer.uuid,
    foreign_keys=[CustomerMailingAddress.parent_uuid],
    collection_class=ordering_list('preference', count_from=1),
    order_by=CustomerMailingAddress.preference,
    cascade='all, delete-orphan')

Customer.address = orm.relationship(
    CustomerMailingAddress,
    primaryjoin=sa.and_(
        CustomerMailingAddress.parent_uuid == Customer.uuid,
        CustomerMailingAddress.preference == 1),
    foreign_keys=[CustomerMailingAddress.parent_uuid],
    uselist=False,
    viewonly=True)


class CustomerNote(Note):
    """
    Represents a note attached to a customer.
    """
    __mapper_args__ = {'polymorphic_identity': 'Customer'}

    customer = orm.relationship(
        Customer,
        primaryjoin='Customer.uuid == CustomerNote.parent_uuid',
        foreign_keys='CustomerNote.parent_uuid',
        doc="""
        Reference to the customer to which this note is attached.
        """,
        backref=orm.backref(
            'notes',
            primaryjoin='CustomerNote.parent_uuid == Customer.uuid',
            foreign_keys='CustomerNote.parent_uuid',
            order_by='CustomerNote.created',
            cascade='all, delete-orphan',
            doc="""
            Sequence of notes which belong to the customer.
            """))


@six.python_2_unicode_compatible
class CustomerGroup(Base):
    """
    Represents an arbitrary group to which customers may belong.
    """
    __tablename__ = 'customer_group'
    __versioned__ = {}

    uuid = uuid_column()
    id = sa.Column(sa.String(length=20))
    name = sa.Column(sa.String(length=255))

    def __str__(self):
        return self.name or ''


class CustomerGroupAssignment(Base):
    """
    Represents the assignment of a customer to a group.
    """
    __tablename__ = 'customer_x_group'
    __table_args__ = (
        sa.ForeignKeyConstraint(['group_uuid'], ['customer_group.uuid'], name='customer_x_group_fk_group'),
        sa.ForeignKeyConstraint(['customer_uuid'], ['customer.uuid'], name='customer_x_group_fk_customer'),
    )
    __versioned__ = {}

    uuid = uuid_column()
    customer_uuid = sa.Column(sa.String(length=32), nullable=False)
    group_uuid = sa.Column(sa.String(length=32), nullable=False)
    ordinal = sa.Column(sa.Integer(), nullable=False)

    group = orm.relationship(CustomerGroup)


Customer._groups = orm.relationship(
    CustomerGroupAssignment, backref='customer',
    collection_class=ordering_list('ordinal', count_from=1),
    order_by=CustomerGroupAssignment.ordinal,
    cascade='save-update, merge, delete, delete-orphan')

Customer.groups = association_proxy(
    '_groups', 'group',
    getset_factory=getset_factory,
    creator=lambda g: CustomerGroupAssignment(group=g))


class CustomerPerson(Base):
    """
    Represents the association between a person and a customer account.
    """
    __tablename__ = 'customer_x_person'
    __table_args__ = (
        sa.ForeignKeyConstraint(['customer_uuid'], ['customer.uuid'], name='customer_x_person_fk_customer'),
        sa.ForeignKeyConstraint(['person_uuid'], ['person.uuid'], name='customer_x_person_fk_person'),
        sa.Index('customer_x_person_ix_customer', 'customer_uuid'),
        sa.Index('customer_x_person_ix_person', 'person_uuid'),
    )
    __versioned__ = {}

    uuid = uuid_column()
    customer_uuid = sa.Column(sa.String(length=32), nullable=False)
    person_uuid = sa.Column(sa.String(length=32), nullable=False)
    ordinal = sa.Column(sa.Integer(), nullable=False)

    customer = orm.relationship(Customer, back_populates='_people')

    person = orm.relationship(Person)


Customer._people = orm.relationship(
    CustomerPerson, back_populates='customer',
    primaryjoin=CustomerPerson.customer_uuid == Customer.uuid,
    collection_class=ordering_list('ordinal', count_from=1),
    order_by=CustomerPerson.ordinal,
    cascade='save-update, merge, delete, delete-orphan')

Customer.people = association_proxy(
    '_people', 'person',
    getset_factory=getset_factory,
    creator=lambda p: CustomerPerson(person=p))

Customer._person = orm.relationship(
    CustomerPerson,
    primaryjoin=sa.and_(
        CustomerPerson.customer_uuid == Customer.uuid,
        CustomerPerson.ordinal == 1),
    uselist=False,
    viewonly=True)

Customer.person = association_proxy(
    '_person', 'person',
    getset_factory=getset_factory)

Person._customers = orm.relationship(
    CustomerPerson,
    primaryjoin=CustomerPerson.person_uuid == Person.uuid,
    viewonly=True)

Person.customers = association_proxy('_customers', 'customer',
                                     getset_factory=getset_factory,
                                     creator=lambda c: CustomerPerson(customer=c))


class PendingCustomer(Base):
    """
    A "pending" customer record, used for new customer entry workflow.
    """
    __tablename__ = 'pending_customer'
    __table_args__ = (
        sa.ForeignKeyConstraint(['user_uuid'], ['user.uuid'], name='pending_customer_fk_user'),
    )

    uuid = uuid_column()

    user_uuid = sa.Column(sa.String(length=32), nullable=False)
    user = orm.relationship(
        User,
        doc="""
        Referencef to the :class:`~rattail:rattail.db.model.User` who
        first entered the record.
        """)

    created = sa.Column(sa.DateTime(), nullable=False, default=datetime.datetime.utcnow, doc="""
    Timestamp when the record was first created.
    """)

    # Customer fields
    id = sa.Column(sa.String(length=20), nullable=True)

    # Person fields
    first_name = sa.Column(sa.String(length=50), nullable=True)
    middle_name = sa.Column(sa.String(length=50), nullable=True)
    last_name = sa.Column(sa.String(length=50), nullable=True)
    display_name = sa.Column(sa.String(length=100), nullable=True)

    # Phone fields
    phone_number = sa.Column(sa.String(length=20), nullable=True)
    phone_type = sa.Column(sa.String(length=15), nullable=True)

    # Email fields
    email_address = sa.Column(sa.String(length=255), nullable=True)
    email_type = sa.Column(sa.String(length=15), nullable=True)

    # Address fields
    address_street = sa.Column(sa.String(length=100), nullable=True)
    address_street2 = sa.Column(sa.String(length=100), nullable=True)
    address_city = sa.Column(sa.String(length=60), nullable=True)
    address_state = sa.Column(sa.String(length=2), nullable=True)
    address_zipcode = sa.Column(sa.String(length=10), nullable=True)
    address_type = sa.Column(sa.String(length=15), nullable=True)

    # workflow fields
    status_code = sa.Column(sa.Integer(), nullable=True, doc="""
    Status indicator for the new customer record.
    """)

    def __str__(self):
        if six.PY2:
            return (self.display_name or "").encode('utf_8')
        return self.display_name or ""

    if six.PY2:
        def __unicode__(self):
            return self.display_name or ""