source: rattail/rattail/batch/purchase.py @ 3336da3

Last change on this file since 3336da3 was 3336da3, checked in by Lance Edgar <ledgar@…>, 10 months ago

Aggregate when adding truck dump child row already present in parent

  • Property mode set to 100644
File size: 62.8 KB
Line 
1# -*- coding: utf-8; -*-
2################################################################################
3#
4#  Rattail -- Retail Software Framework
5#  Copyright © 2010-2019 Lance Edgar
6#
7#  This file is part of Rattail.
8#
9#  Rattail is free software: you can redistribute it and/or modify it under the
10#  terms of the GNU General Public License as published by the Free Software
11#  Foundation, either version 3 of the License, or (at your option) any later
12#  version.
13#
14#  Rattail is distributed in the hope that it will be useful, but WITHOUT ANY
15#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16#  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17#  details.
18#
19#  You should have received a copy of the GNU General Public License along with
20#  Rattail.  If not, see <http://www.gnu.org/licenses/>.
21#
22################################################################################
23"""
24Handler for purchase order batches
25"""
26
27from __future__ import unicode_literals, absolute_import
28
29import logging
30
31import six
32from sqlalchemy import orm
33
34from rattail.db import model, api
35from rattail.gpc import GPC
36from rattail.batch import BatchHandler
37from rattail.time import make_utc
38from rattail.vendors.invoices import require_invoice_parser
39
40
41log = logging.getLogger(__name__)
42
43
44class PurchaseBatchHandler(BatchHandler):
45    """
46    Handler for purchase order batches.
47    """
48    batch_model_class = model.PurchaseBatch
49
50    def allow_cases(self):
51        """
52        Must return boolean indicating whether "cases" should be generally
53        allowed, for sake of quantity input etc.
54        """
55        return self.config.getbool('rattail.batch', 'purchase.allow_cases',
56                                   default=True)
57
58    def allow_expired_credits(self):
59        """
60        Must return boolean indicating whether "expired" credits should be
61        tracked.  In practice, this should either en- or dis-able various UI
62        elements which involves expired product.
63        """
64        return self.config.getbool('rattail.batch', 'purchase.allow_expired_credits',
65                                   default=True)
66
67    def should_populate(self, batch):
68        # TODO: this probably should change soon, for now this works..
69        return batch.purchase and batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
70                                                 self.enum.PURCHASE_BATCH_MODE_COSTING)
71
72    def populate(self, batch, progress=None):
73        assert batch.purchase and batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
74                                                 self.enum.PURCHASE_BATCH_MODE_COSTING)
75        batch.order_quantities_known = True
76
77        def append(item, i):
78            row = model.PurchaseBatchRow()
79            product = item.product
80            row.item = item
81            row.product = product
82            if product:
83                row.upc = product.upc
84                row.item_id = product.item_id
85            else:
86                row.upc = item.upc
87                row.item_id = item.item_id
88            row.cases_ordered = item.cases_ordered
89            row.units_ordered = item.units_ordered
90            row.cases_received = item.cases_received
91            row.units_received = item.units_received
92            row.po_unit_cost = item.po_unit_cost
93            row.po_total = item.po_total
94            if batch.mode == self.enum.PURCHASE_BATCH_MODE_COSTING:
95                row.invoice_unit_cost = item.invoice_unit_cost
96                row.invoice_total = item.invoice_total
97            self.add_row(batch, row)
98
99        self.progress_loop(append, batch.purchase.items, progress,
100                           message="Adding initial rows to batch")
101
102        # TODO: should(n't) this be handled elsewhere?
103        session = orm.object_session(batch)
104        session.flush()
105        self.refresh_batch_status(batch)
106
107    def populate_from_truck_dump_invoice(self, batch, progress=None):
108        child_batch = batch
109        parent_batch = child_batch.truck_dump_batch
110        session = orm.object_session(child_batch)
111
112        parser = require_invoice_parser(child_batch.invoice_parser_key)
113        parser.session = session
114
115        parser.vendor = api.get_vendor(session, parser.vendor_key)
116        if parser.vendor is not child_batch.vendor:
117            raise RuntimeError("Parser is for vendor '{}' but batch is for: {}".format(
118                parser.vendor_key, child_batch.vendor))
119
120        path = child_batch.filepath(self.config, child_batch.invoice_file)
121        child_batch.invoice_date = parser.parse_invoice_date(path)
122        child_batch.order_quantities_known = True
123
124        def append(invoice_row, i):
125            row = self.make_row_from_invoice(child_batch, invoice_row)
126            self.add_row(child_batch, row)
127
128        self.progress_loop(append, list(parser.parse_rows(path)), progress,
129                           message="Adding initial rows to batch")
130
131        if parent_batch.truck_dump_children_first:
132            # children first, so should add rows to parent batch now
133            session.flush()
134
135            def append(child_row, i):
136                if not child_row.out_of_stock:
137
138                    # if row for this product already exists in parent, must aggregate
139                    parent_row = self.locate_parent_row_for_child(parent_batch, child_row)
140                    if parent_row:
141
142                        # confirm 'case_quantity' matches
143                        if parent_row.case_quantity != child_row.case_quantity:
144                            raise ValueError("differing 'case_quantity' for item {}: {}".format(
145                                child_row.item_entry, child_row.description))
146
147                        # confirm 'out_of_stock' matches
148                        if parent_row.out_of_stock != child_row.out_of_stock:
149                            raise ValueError("differing 'out_of_stock' for item {}: {}".format(
150                                cihld_row.item_entry, child_row.description))
151
152                        # confirm 'invoice_unit_cost' matches
153                        if parent_row.invoice_unit_cost != child_row.invoice_unit_cost:
154                            raise ValueError("differing 'invoice_unit_cost' for item {}: {}".format(
155                                cihld_row.item_entry, child_row.description))
156
157                        # confirm 'invoice_case_cost' matches
158                        if parent_row.invoice_case_cost != child_row.invoice_case_cost:
159                            raise ValueError("differing 'invoice_case_cost' for item {}: {}".format(
160                                cihld_row.item_entry, child_row.description))
161
162                        # add 'ordered' quantities
163                        if child_row.cases_ordered:
164                            parent_row.cases_ordered = (parent_row.cases_ordered or 0) + child_row.cases_ordered
165                        if child_row.units_ordered:
166                            parent_row.units_ordered = (parent_row.units_ordered or 0) + child_row.units_ordered
167
168                        # add 'shipped' quantities
169                        if child_row.cases_shipped:
170                            parent_row.cases_shipped = (parent_row.cases_shipped or 0) + child_row.cases_shipped
171                        if child_row.units_shipped:
172                            parent_row.units_shipped = (parent_row.units_shipped or 0) + child_row.units_shipped
173
174                        # add 'invoice_total' quantities
175                        if child_row.invoice_total:
176                            parent_row.invoice_total = (parent_row.invoice_total or 0) + child_row.invoice_total
177
178                    else: # new product; simply add new row to parent
179                        parent_row = self.make_parent_row_from_child(child_row)
180                        self.add_row(parent_batch, parent_row)
181
182            self.progress_loop(append, child_batch.active_rows(), progress,
183                               message="Adding rows to parent batch")
184
185        else: # children last, so should make parent claims now
186            self.make_truck_dump_claims_for_child_batch(child_batch, progress=progress)
187
188        self.refresh_batch_status(parent_batch)
189
190    def locate_parent_row_for_child(self, parent_batch, child_row):
191        """
192        Locate a row within parent batch, which "matches" given row from child
193        batch.  May return ``None`` if no match found.
194        """
195        if child_row.product_uuid:
196            rows = [row for row in parent_batch.active_rows()
197                    if row.product_uuid == child_row.product_uuid]
198            if rows:
199                return rows[0]
200
201        elif child_row.item_entry:
202            rows = [row for row in parent_batch.active_rows()
203                    if row.product_uuid is None
204                    and row.item_entry == child_row.item_entry]
205            if rows:
206                return rows[0]
207
208    def make_row_from_invoice(self, batch, invoice_row):
209        row = model.PurchaseBatchRow()
210        row.item_entry = invoice_row.item_entry
211        row.upc = invoice_row.upc
212        row.vendor_code = invoice_row.vendor_code
213        row.brand_name = invoice_row.brand_name
214        row.description = invoice_row.description
215        row.size = invoice_row.size
216        row.case_quantity = invoice_row.case_quantity
217        row.cases_ordered = invoice_row.ordered_cases
218        row.units_ordered = invoice_row.ordered_units
219        row.cases_shipped = invoice_row.shipped_cases
220        row.units_shipped = invoice_row.shipped_units
221        row.out_of_stock = invoice_row.out_of_stock
222        row.invoice_unit_cost = invoice_row.unit_cost
223        row.invoice_total = invoice_row.total_cost
224        row.invoice_case_cost = invoice_row.case_cost
225        return row
226
227    def make_parent_row_from_child(self, child_row):
228        row = model.PurchaseBatchRow()
229        row.item_entry = child_row.item_entry
230        row.upc = child_row.upc
231        row.vendor_code = child_row.vendor_code
232        row.brand_name = child_row.brand_name
233        row.description = child_row.description
234        row.size = child_row.size
235        row.case_quantity = child_row.case_quantity
236        row.cases_ordered = child_row.cases_ordered
237        row.units_ordered = child_row.units_ordered
238        row.cases_shipped = child_row.cases_shipped
239        row.units_shipped = child_row.units_shipped
240        row.out_of_stock = child_row.out_of_stock
241        row.invoice_unit_cost = child_row.invoice_unit_cost
242        row.invoice_total = child_row.invoice_total
243        row.invoice_case_cost = child_row.invoice_case_cost
244        return row
245
246    def make_truck_dump_claims_for_child_batch(self, batch, progress=None):
247        """
248        Make all "claims" against a truck dump, for the given child batch.
249        This assumes no claims exist for the child batch at time of calling,
250        and that the truck dump batch is complete and not yet executed.
251        """
252        session = orm.object_session(batch)
253        truck_dump_rows = batch.truck_dump_batch.active_rows()
254        child_rows = batch.active_rows()
255
256        # organize truck dump by product and UPC
257        truck_dump_by_product = {}
258        truck_dump_by_upc = {}
259
260        def organize_parent(row, i):
261            if row.product:
262                truck_dump_by_product.setdefault(row.product.uuid, []).append(row)
263            if row.upc:
264                truck_dump_by_upc.setdefault(row.upc, []).append(row)
265
266        self.progress_loop(organize_parent, truck_dump_rows, progress,
267                           message="Organizing truck dump parent rows")
268
269        # organize child batch by product and UPC
270        child_by_product = {}
271        child_by_upc = {}
272
273        def organize_child(row, i):
274            if row.product:
275                child_by_product.setdefault(row.product.uuid, []).append(row)
276            if row.upc:
277                child_by_upc.setdefault(row.upc, []).append(row)
278
279        self.progress_loop(organize_child, child_rows, progress,
280                           message="Organizing truck dump child rows")
281
282        # okay then, let's go through all our organized rows, and make claims
283
284        def make_claims(child_product, i):
285            uuid, child_product_rows = child_product
286            if uuid in truck_dump_by_product:
287                truck_dump_product_rows = truck_dump_by_product[uuid]
288                for truck_dump_row in truck_dump_product_rows:
289                    self.make_truck_dump_claims(truck_dump_row, child_product_rows)
290
291        self.progress_loop(make_claims, child_by_product.items(), progress,
292                           count=len(child_by_product),
293                           message="Claiming parent rows for child") # (pass #1)
294
295    def make_truck_dump_claims(self, truck_dump_row, child_rows):
296
297        # first we go through the truck dump parent row, and calculate all
298        # "present", and "claimed" vs. "pending" product quantities
299
300        # cases_received
301        cases_received = truck_dump_row.cases_received or 0
302        cases_received_claimed = sum([claim.cases_received or 0
303                                      for claim in truck_dump_row.claims])
304        cases_received_pending = cases_received - cases_received_claimed
305
306        # units_received
307        units_received = truck_dump_row.units_received or 0
308        units_received_claimed = sum([claim.units_received or 0
309                                      for claim in truck_dump_row.claims])
310        units_received_pending = units_received - units_received_claimed
311
312        # cases_damaged
313        cases_damaged = truck_dump_row.cases_damaged or 0
314        cases_damaged_claimed = sum([claim.cases_damaged or 0
315                                     for claim in truck_dump_row.claims])
316        cases_damaged_pending = cases_damaged - cases_damaged_claimed
317
318        # units_damaged
319        units_damaged = truck_dump_row.units_damaged or 0
320        units_damaged_claimed = sum([claim.units_damaged or 0
321                                     for claim in truck_dump_row.claims])
322        units_damaged_pending = units_damaged - units_damaged_claimed
323
324        # cases_expired
325        cases_expired = truck_dump_row.cases_expired or 0
326        cases_expired_claimed = sum([claim.cases_expired or 0
327                                     for claim in truck_dump_row.claims])
328        cases_expired_pending = cases_expired - cases_expired_claimed
329
330        # units_expired
331        units_expired = truck_dump_row.units_expired or 0
332        units_expired_claimed = sum([claim.units_expired or 0
333                                     for claim in truck_dump_row.claims])
334        units_expired_pending = units_expired - units_expired_claimed
335
336        # TODO: should be calculating mispicks here too, right?
337
338        def make_claim(child_row):
339            c = model.PurchaseBatchRowClaim()
340            c.claiming_row = child_row
341            truck_dump_row.claims.append(c)
342            return c
343
344        for child_row in child_rows:
345
346            # stop now if everything in this parent row is accounted for
347            if not (cases_received_pending or units_received_pending
348                    or cases_damaged_pending or units_damaged_pending
349                    or cases_expired_pending or units_expired_pending):
350                break
351
352            # for each child row we also calculate all "present", and "claimed"
353            # vs. "pending" product quantities
354
355            # cases_ordered
356            cases_ordered = child_row.cases_ordered or 0
357            cases_ordered_claimed = sum([(claim.cases_received or 0)
358                                         + (claim.cases_damaged or 0)
359                                         + (claim.cases_expired or 0)
360                                         for claim in child_row.truck_dump_claims])
361            cases_ordered_pending = cases_ordered - cases_ordered_claimed
362
363            # units_ordered
364            units_ordered = child_row.units_ordered or 0
365            units_ordered_claimed = sum([(claim.units_received or 0)
366                                         + (claim.units_damaged or 0)
367                                         + (claim.units_expired or 0)
368                                         for claim in child_row.truck_dump_claims])
369            units_ordered_pending = units_ordered - units_ordered_claimed
370
371            # skip this child row if everything in it is accounted for
372            if not (cases_ordered_pending or units_ordered_pending):
373                continue
374
375            # there should only be one claim for this parent/child combo
376            claim = None
377
378            # let's cache this
379            case_quantity = child_row.case_quantity
380
381            # make case claims
382            if cases_ordered_pending and cases_received_pending:
383                claim = claim or make_claim(child_row)
384                if cases_received_pending >= cases_ordered_pending:
385                    claim.cases_received = (claim.cases_received or 0) + cases_ordered_pending
386                    child_row.cases_received = (child_row.cases_received or 0) + cases_ordered_pending
387                    cases_received_pending -= cases_ordered_pending
388                    cases_ordered_pending = 0
389                else: # ordered > received
390                    claim.cases_received = (claim.cases_received or 0) + cases_received_pending
391                    child_row.cases_received = (child_row.cases_received or 0) + cases_received_pending
392                    cases_ordered_pending -= cases_received_pending
393                    cases_received_pending = 0
394                self.refresh_row(child_row)
395            if cases_ordered_pending and cases_damaged_pending:
396                claim = claim or make_claim(child_row)
397                if cases_damaged_pending >= cases_ordered_pending:
398                    claim.cases_damaged = (claim.cases_damaged or 0) + cases_ordered_pending
399                    child_row.cases_damaged = (child_row.cases_damaged or 0) + cases_ordered_pending
400                    cases_damaged_pending -= cases_ordered_pending
401                    cases_ordered_pending = 0
402                else: # ordered > damaged
403                    claim.cases_damaged = (claim.cases_damaged or 0) + cases_damaged_pending
404                    child_row.cases_damaged = (child_row.cases_damaged or 0) + cases_damaged_pending
405                    cases_ordered_pending -= cases_damaged_pending
406                    cases_damaged_pending = 0
407                self.refresh_row(child_row)
408            if cases_ordered_pending and cases_expired_pending:
409                claim = claim or make_claim(child_row)
410                if cases_expired_pending >= cases_ordered_pending:
411                    claim.cases_expired = (claim.cases_expired or 0) + cases_ordered_pending
412                    child_row.cases_expired = (child_row.cases_expired or 0) + cases_ordered_pending
413                    cases_expired_pending -= cases_ordered_pending
414                    cases_ordered_pending = 0
415                else: # ordered > expired
416                    claim.cases_expired = (claim.cases_expired or 0) + cases_expired_pending
417                    child_row.cases_expired = (child_row.cases_expired or 0) + cases_expired_pending
418                    cases_ordered_pending -= cases_expired_pending
419                    cases_expired_pending = 0
420                self.refresh_row(child_row)
421
422            # make unit claims
423            if units_ordered_pending and units_received_pending:
424                claim = claim or make_claim(child_row)
425                if units_received_pending >= units_ordered_pending:
426                    claim.units_received = (claim.units_received or 0) + units_ordered_pending
427                    child_row.units_received = (child_row.units_received or 0) + units_ordered_pending
428                    units_received_pending -= units_ordered_pending
429                    units_ordered_pending = 0
430                else: # ordered > received
431                    claim.units_received = (claim.units_received or 0) + units_received_pending
432                    child_row.units_received = (child_row.units_received or 0) + units_received_pending
433                    units_ordered_pending -= units_received_pending
434                    units_received_pending = 0
435                self.refresh_row(child_row)
436            if units_ordered_pending and units_damaged_pending:
437                claim = claim or make_claim(child_row)
438                if units_damaged_pending >= units_ordered_pending:
439                    claim.units_damaged = (claim.units_damaged or 0) + units_ordered_pending
440                    child_row.units_damaged = (child_row.units_damaged or 0) + units_ordered_pending
441                    units_damaged_pending -= units_ordered_pending
442                    units_ordered_pending = 0
443                else: # ordered > damaged
444                    claim.units_damaged = (claim.units_damaged or 0) + units_damaged_pending
445                    child_row.units_damaged = (child_row.units_damaged or 0) + units_damaged_pending
446                    units_ordered_pending -= units_damaged_pending
447                    units_damaged_pending = 0
448                self.refresh_row(child_row)
449            if units_ordered_pending and units_expired_pending:
450                claim = claim or make_claim(child_row)
451                if units_expired_pending >= units_ordered_pending:
452                    claim.units_expired = (claim.units_expired or 0) + units_ordered_pending
453                    child_row.units_expired = (child_row.units_expired or 0) + units_ordered_pending
454                    units_expired_pending -= units_ordered_pending
455                    units_ordered_pending = 0
456                else: # ordered > expired
457                    claim.units_expired = (claim.units_expired or 0) + units_expired_pending
458                    child_row.units_expired = (child_row.units_expired or 0) + units_expired_pending
459                    units_ordered_pending -= units_expired_pending
460                    units_expired_pending = 0
461                self.refresh_row(child_row)
462
463            # claim units from parent, as cases for child.  note that this
464            # crosses the case/unit boundary, but is considered "safe" because
465            # we assume the child row has correct case quantity even if parent
466            # row has a different one.
467            if cases_ordered_pending and units_received_pending:
468                received = units_received_pending // case_quantity
469                if received:
470                    claim = claim or make_claim(child_row)
471                    if received >= cases_ordered_pending:
472                        claim.cases_received = (claim.cases_received or 0) + cases_ordered_pending
473                        child_row.cases_received = (child_row.units_received or 0) + cases_ordered_pending
474                        units_received_pending -= (cases_ordered_pending * case_quantity)
475                        cases_ordered_pending = 0
476                    else: # ordered > received
477                        claim.cases_received = (claim.cases_received or 0) + received
478                        child_row.cases_received = (child_row.units_received or 0) + received
479                        cases_ordered_pending -= received
480                        units_received_pending -= (received * case_quantity)
481                    self.refresh_row(child_row)
482            if cases_ordered_pending and units_damaged_pending:
483                damaged = units_damaged_pending // case_quantity
484                if damaged:
485                    claim = claim or make_claim(child_row)
486                    if damaged >= cases_ordered_pending:
487                        claim.cases_damaged = (claim.cases_damaged or 0) + cases_ordered_pending
488                        child_row.cases_damaged = (child_row.units_damaged or 0) + cases_ordered_pending
489                        units_damaged_pending -= (cases_ordered_pending * case_quantity)
490                        cases_ordered_pending = 0
491                    else: # ordered > damaged
492                        claim.cases_damaged = (claim.cases_damaged or 0) + damaged
493                        child_row.cases_damaged = (child_row.units_damaged or 0) + damaged
494                        cases_ordered_pending -= damaged
495                        units_damaged_pending -= (damaged * case_quantity)
496                    self.refresh_row(child_row)
497            if cases_ordered_pending and units_expired_pending:
498                expired = units_expired_pending // case_quantity
499                if expired:
500                    claim = claim or make_claim(child_row)
501                    if expired >= cases_ordered_pending:
502                        claim.cases_expired = (claim.cases_expired or 0) + cases_ordered_pending
503                        child_row.cases_expired = (child_row.units_expired or 0) + cases_ordered_pending
504                        units_expired_pending -= (cases_ordered_pending * case_quantity)
505                        cases_ordered_pending = 0
506                    else: # ordered > expired
507                        claim.cases_expired = (claim.cases_expired or 0) + expired
508                        child_row.cases_expired = (child_row.units_expired or 0) + expired
509                        cases_ordered_pending -= expired
510                        units_expired_pending -= (expired * case_quantity)
511                    self.refresh_row(child_row)
512
513            # if necessary, try to claim cases from parent, as units for child.
514            # this also crosses the case/unit boundary but is considered safe
515            # only if the case quantity matches between child and parent rows.
516            # (otherwise who knows what could go wrong.)
517            if case_quantity == truck_dump_row.case_quantity:
518                if units_ordered_pending and cases_received_pending:
519                    received = cases_received_pending * case_quantity
520                    claim = claim or make_claim(child_row)
521                    if received >= units_ordered_pending:
522                        claim.units_received = (claim.units_received or 0) + units_ordered_pending
523                        child_row.units_received = (child_row.units_received or 0) + units_ordered_pending
524                        leftover = received % units_ordered_pending
525                        if leftover == 0:
526                            cases_received_pending -= (received // units_ordered_pending)
527                        else:
528                            cases_received_pending -= (received // units_ordered_pending) - 1
529                            units_received_pending += leftover
530                        units_ordered_pending = 0
531                    else: # ordered > received
532                        claim.units_received = (claim.units_received or 0) + received
533                        child_row.units_received = (child_row.units_received or 0) + received
534                        units_ordered_pending -= received
535                        cases_received_pending = 0
536                    self.refresh_row(child_row)
537                if units_ordered_pending and cases_damaged_pending:
538                    damaged = cases_damaged_pending * case_quantity
539                    claim = claim or make_claim(child_row)
540                    if damaged >= units_ordered_pending:
541                        claim.units_damaged = (claim.units_damaged or 0) + units_ordered_pending
542                        child_row.units_damaged = (child_row.units_damaged or 0) + units_ordered_pending
543                        leftover = damaged % units_ordered_pending
544                        if leftover == 0:
545                            cases_damaged_pending -= (damaged // units_ordered_pending)
546                        else:
547                            cases_damaged_pending -= (damaged // units_ordered_pending) - 1
548                            units_damaged_pending += leftover
549                        units_ordered_pending = 0
550                    else: # ordered > damaged
551                        claim.units_damaged = (claim.units_damaged or 0) + damaged
552                        child_row.units_damaged = (child_row.units_damaged or 0) + damaged
553                        units_ordered_pending -= damaged
554                        cases_damaged_pending = 0
555                    self.refresh_row(child_row)
556                if units_ordered_pending and cases_expired_pending:
557                    expired = cases_expired_pending * case_quantity
558                    claim = claim or make_claim(child_row)
559                    if expired >= units_ordered_pending:
560                        claim.units_expired = (claim.units_expired or 0) + units_ordered_pending
561                        child_row.units_expired = (child_row.units_expired or 0) + units_ordered_pending
562                        leftover = expired % units_ordered_pending
563                        if leftover == 0:
564                            cases_expired_pending -= (expired // units_ordered_pending)
565                        else:
566                            cases_expired_pending -= (expired // units_ordered_pending) - 1
567                            units_expired_pending += leftover
568                        units_ordered_pending = 0
569                    else: # ordered > expired
570                        claim.units_expired = (claim.units_expired or 0) + expired
571                        child_row.units_expired = (child_row.units_expired or 0) + expired
572                        units_ordered_pending -= expired
573                        cases_expired_pending = 0
574                    self.refresh_row(child_row)
575
576            # refresh the parent row, to reflect any new claim(s) made
577            self.refresh_row(truck_dump_row)
578
579    def clone_truck_dump_credit(self, truck_dump_credit, child_row):
580        """
581        Clone a credit record from a truck dump, onto the given child row.
582        """
583        child_batch = child_row.batch
584        child_credit = model.PurchaseBatchCredit()
585        self.copy_credit_attributes(truck_dump_credit, child_credit)
586        child_credit.date_ordered = child_batch.date_ordered
587        child_credit.date_shipped = child_batch.date_shipped
588        child_credit.date_received = child_batch.date_received
589        child_credit.invoice_date = child_batch.invoice_date
590        child_credit.invoice_number = child_batch.invoice_number
591        child_credit.invoice_line_number = child_row.invoice_line_number
592        child_credit.invoice_case_cost = child_row.invoice_case_cost
593        child_credit.invoice_unit_cost = child_row.invoice_unit_cost
594        child_credit.invoice_total = child_row.invoice_total
595        child_row.credits.append(child_credit)
596        return child_credit
597
598    # TODO: surely this should live elsewhere
599    def calc_best_fit(self, units, case_quantity):
600        case_quantity = case_quantity or 1
601        if case_quantity == 1:
602            return 0, units
603        cases = units // case_quantity
604        if cases:
605            return cases, units - (cases * case_quantity)
606        return 0, units
607
608    def refresh(self, batch, progress=None):
609
610        # reset PO total for ordering batch
611        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
612            batch.po_total = 0
613
614        # reset invoice total for receiving and costing batch
615        elif batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
616                            self.enum.PURCHASE_BATCH_MODE_COSTING):
617            batch.invoice_total = 0
618
619        # refresh all rows etc. per usual
620        result = super(PurchaseBatchHandler, self).refresh(batch, progress=progress)
621        if result:
622
623            # here begins some extra magic for truck dump receiving batches
624            if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
625                session = orm.object_session(batch)
626                session.flush()
627
628                if batch.is_truck_dump_parent():
629
630                    # will try to establish new claims against the parent
631                    # batch, where possible
632                    unclaimed = [row for row in batch.active_rows()
633                                 if row.status_code in (row.STATUS_TRUCKDUMP_UNCLAIMED,
634                                                        row.STATUS_TRUCKDUMP_PARTCLAIMED)]
635                    for row in unclaimed:
636                        if row.product_uuid: # only support rows with product for now
637                            self.make_truck_dump_claims_for_parent_row(row)
638
639                    # all rows should be refreshed now, but batch status still needs it
640                    self.refresh_batch_status(batch)
641                    for child in batch.truck_dump_children:
642                        self.refresh_batch_status(child)
643
644                elif batch.is_truck_dump_child():
645
646                    # will try to establish claims against the parent batch,
647                    # for each "incomplete" row (i.e. those with unclaimed
648                    # order quantities)
649                    incomplete = [row for row in batch.active_rows()
650                                  if row.status_code in (row.STATUS_INCOMPLETE,
651                                                         row.STATUS_ORDERED_RECEIVED_DIFFER)]
652                    for row in incomplete:
653                        if row.product_uuid: # only support rows with product for now
654                            parent_rows = [parent_row for parent_row in batch.truck_dump_batch.active_rows()
655                                           if parent_row.product_uuid == row.product_uuid]
656                            for parent_row in parent_rows:
657                                self.make_truck_dump_claims(parent_row, [row])
658                                if row.status_code not in (row.STATUS_INCOMPLETE,
659                                                           row.STATUS_ORDERED_RECEIVED_DIFFER):
660                                    break
661
662                    # all rows should be refreshed now, but batch status still needs it
663                    self.refresh_batch_status(batch.truck_dump_batch)
664                    self.refresh_batch_status(batch)
665
666        return result
667
668    def refresh_batch_status(self, batch):
669        rows = batch.active_rows()
670
671        # "unknown product" is the most egregious status; we'll "prefer" it
672        # over all others in order to bring it to user's attention
673        if any([row.status_code == row.STATUS_PRODUCT_NOT_FOUND for row in rows]):
674            batch.status_code = batch.STATUS_UNKNOWN_PRODUCT
675
676        # truck dump parent batch status should reflect how much is (un)claimed
677        elif batch.is_truck_dump_parent():
678
679            # empty batch is considered "ok"
680            if not rows:
681                batch.status_code = batch.STATUS_OK
682
683            # batch is "claimed" only if all rows are "settled" so to speak
684            elif all([row.status_code in (row.STATUS_TRUCKDUMP_CLAIMED,
685                                          row.STATUS_OK)
686                      for row in rows]):
687                batch.status_code = batch.STATUS_TRUCKDUMP_CLAIMED
688
689            # otherwise just call it "unclaimed"
690            else:
691                batch.status_code = batch.STATUS_TRUCKDUMP_UNCLAIMED
692
693        # for now anything else is considered ok
694        else:
695            batch.status_code = batch.STATUS_OK
696
697    def locate_product_for_entry(self, session, entry, lookup_by_code=True):
698        """
699        Try to locate the product represented by the given "entry" - which is
700        assumed to be a "raw" string, e.g. as obtained from scanner or other
701        user input, or from a vendor-supplied spreadsheet etc.  (In other words
702        this method is not told "what" sort of entry it is being given.)
703
704        :param lookup_by_code: If set to ``False``, then the method will
705           attempt a lookup *only* on the product key field (either ``upc`` or
706           ``item_id`` depending on config).  If set to ``True`` (the default)
707           then the method will also attempt a lookup in the ``ProductCode``
708           table, aka. alternate codes.
709        """
710        # try to locate product by uuid before other, more specific key
711        product = session.query(model.Product).get(entry)
712        if product:
713            return product
714
715        product_key = self.config.product_key()
716        if product_key == 'upc':
717
718            if entry.isdigit():
719
720                # we first assume the user entry *does* include check digit
721                provided = GPC(entry, calc_check_digit=False)
722                product = api.get_product_by_upc(session, provided)
723                if product:
724                    return product
725
726                # but we can also calculate a check digit and try that
727                checked = GPC(entry, calc_check_digit='upc')
728                product = api.get_product_by_upc(session, checked)
729                if product:
730                    return product
731
732        elif product_key == 'item_id':
733
734            # try to locate product by item_id
735            product = api.get_product_by_item_id(session, entry)
736            if product:
737                return product
738
739        # if we made it this far, lookup by product key failed.
740
741        # okay then, let's maybe attempt lookup by "alternate" code
742        if lookup_by_code:
743            product = api.get_product_by_code(session, entry)
744            if product:
745                return product
746
747    def locate_product(self, row, session=None, vendor=None):
748        """
749        Try to locate the product represented by the given row.  Default
750        behavior here, is to do a simple lookup on either ``Product.upc`` or
751        ``Product.item_id``, depending on which is configured as your product
752        key field.
753        """
754        if not session:
755            session = orm.object_session(row)
756        product_key = self.config.product_key()
757
758        if product_key == 'upc':
759            if row.upc:
760                product = api.get_product_by_upc(session, row.upc)
761                if product:
762                    return product
763
764        elif product_key == 'item_id':
765            if row.item_id:
766                product = api.get_product_by_item_id(session, row.item_id)
767                if product:
768                    return product
769
770        # product key didn't work, but vendor item code just might
771        if row.vendor_code:
772            product = api.get_product_by_vendor_code(session, row.vendor_code,
773                                                     vendor=vendor or row.batch.vendor)
774            if product:
775                return product
776
777        # before giving up, let's do a lookup on alt codes too
778        if row.item_entry:
779            product = api.get_product_by_code(session, row.item_entry)
780            if product:
781                return product
782
783    def transform_pack_to_unit(self, row):
784        """
785        Transform the given row, which is assumed to associate with a "pack"
786        item, such that it associates with the "unit" item instead.
787        """
788        if not row.product:
789            return
790        if not row.product.is_pack_item():
791            return
792
793        assert row.batch.is_truck_dump_parent()
794
795        # remove any existing claims for this (parent) row
796        if row.claims:
797            session = orm.object_session(row)
798            del row.claims[:]
799            # set temporary status for the row, if needed.  this is to help
800            # with claiming logic below
801            if row.status_code in (row.STATUS_TRUCKDUMP_PARTCLAIMED,
802                                   row.STATUS_TRUCKDUMP_CLAIMED,
803                                   row.STATUS_TRUCKDUMP_OVERCLAIMED):
804                row.status_code = row.STATUS_TRUCKDUMP_UNCLAIMED
805            session.flush()
806            session.refresh(row)
807
808        # pretty sure this is the only status we're expecting at this point...
809        assert row.status_code == row.STATUS_TRUCKDUMP_UNCLAIMED
810
811        # replace the row's product association
812        pack = row.product
813        unit = pack.unit
814        row.product = unit
815        row.item_id = unit.item_id
816        row.upc = unit.upc
817
818        # set new case quantity, per preferred cost
819        cost = unit.cost_for_vendor(row.batch.vendor)
820        row.case_quantity = (cost.case_size or 1) if cost else 1
821
822        # must recalculate "units received" since those were for the pack item
823        if row.units_received:
824            row.units_received *= pack.pack_size
825
826        # try to establish "claims" between parent and child(ren)
827        self.make_truck_dump_claims_for_parent_row(row)
828
829        # refresh the row itself, so product attributes will be updated
830        self.refresh_row(row)
831
832        # refresh status for the batch(es) proper, just in case this changed things
833        self.refresh_batch_status(row.batch)
834        for child in row.batch.truck_dump_children:
835            self.refresh_batch_status(child)
836
837    def make_truck_dump_claims_for_parent_row(self, row):
838        """
839        Try to establish all "truck dump claims" between parent and children,
840        for the given parent row.
841        """
842        for child in row.batch.truck_dump_children:
843            child_rows = [child_row for child_row in child.active_rows()
844                          if child_row.product_uuid == row.product.uuid]
845            if child_rows:
846                self.make_truck_dump_claims(row, child_rows)
847                if row.status_code not in (row.STATUS_TRUCKDUMP_UNCLAIMED,
848                                           row.STATUS_TRUCKDUMP_PARTCLAIMED):
849                    break
850
851    def refresh_row(self, row, initial=False):
852        """
853        Refreshing a row will A) assume that ``row.product`` is already set to
854        a valid product, or else will attempt to locate the product, and B)
855        update various other fields on the row (description, size, etc.)  to
856        reflect the current product data.  It also will adjust the batch PO
857        total per the row PO total.
858        """
859        batch = row.batch
860
861        # first identify the product, or else we have nothing more to do
862        product = row.product
863        if not product:
864            product = self.locate_product(row)
865            if product:
866                row.product = product
867            else:
868                row.status_code = row.STATUS_PRODUCT_NOT_FOUND
869                return
870
871        # update various (cached) product attributes for the row
872        cost = product.cost_for_vendor(batch.vendor)
873        row.upc = product.upc
874        row.item_id = product.item_id
875        row.brand_name = six.text_type(product.brand or '')
876        row.description = product.description
877        row.size = product.size
878        if product.department:
879            row.department_number = product.department.number
880            row.department_name = product.department.name
881        else:
882            row.department_number = None
883            row.department_name = None
884        row.vendor_code = cost.code if cost else None
885
886        # figure out the effective case quantity, and whether it differs with
887        # what we previously had on file
888        case_quantity_differs = False
889        if cost and cost.case_size:
890            if not row.case_quantity:
891                row.case_quantity = cost.case_size
892            elif row.case_quantity != cost.case_size:
893                if batch.is_truck_dump_parent():
894                    if batch.truck_dump_children_first:
895                        # supposedly our case quantity came from a truck dump
896                        # child row, which we assume to be authoritative
897                        case_quantity_differs = True
898                    else:
899                        # truck dump has no children yet, which means we have
900                        # no special authority for case quantity; therefore
901                        # should treat master cost record as authority
902                        row.case_quantity = cost.case_size
903                else:
904                    case_quantity_differs = True
905
906        # determine PO / invoice unit cost if necessary
907        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING and row.po_unit_cost is None:
908            row.po_unit_cost = self.get_unit_cost(row.product, batch.vendor)
909        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING and row.invoice_unit_cost is None:
910            row.invoice_unit_cost = row.po_unit_cost or (cost.unit_cost if cost else None)
911
912        # update PO / invoice totals for row and batch
913        self.refresh_totals(row, cost, initial)
914
915        # all that's left should be setting status for the row...and that logic
916        # will primarily depend on the 'mode' for this purchase batch
917
918        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
919            row.status_code = row.STATUS_OK
920
921        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
922
923            # first check to see if we have *any* confirmed items
924            if not (row.cases_received or row.units_received or
925                    row.cases_damaged or row.units_damaged or
926                    row.cases_expired or row.units_expired or
927                    row.cases_mispick or row.units_mispick):
928
929                # no, we do not have any confirmed items...
930
931                # TODO: is this right? should row which ordered nothing just be removed?
932                if batch.order_quantities_known and not (row.cases_ordered or row.units_ordered):
933                    row.status_code = row.STATUS_OK
934                # TODO: is this right? should out of stock just be a filter for
935                # the user to specify, or should it affect status?
936                elif row.out_of_stock:
937                    row.status_code = row.STATUS_OUT_OF_STOCK
938                else:
939                    row.status_code = row.STATUS_INCOMPLETE
940
941            else: # we do have some confirmed items
942
943                if batch.is_truck_dump_parent():
944                    confirmed = self.get_units_confirmed(row)
945                    claimed = self.get_units_claimed(row)
946                    if claimed == confirmed:
947                        row.status_code = row.STATUS_TRUCKDUMP_CLAIMED
948                    elif not claimed:
949                        row.status_code = row.STATUS_TRUCKDUMP_UNCLAIMED
950                    elif claimed < confirmed:
951                        row.status_code = row.STATUS_TRUCKDUMP_PARTCLAIMED
952                    elif claimed > confirmed:
953                        row.status_code = row.STATUS_TRUCKDUMP_OVERCLAIMED
954                    else:
955                        raise NotImplementedError
956
957                else: # not truck_dump parent; either "normal" receiving or TD child
958                    if case_quantity_differs:
959                        row.status_code = row.STATUS_CASE_QUANTITY_DIFFERS
960                        row.status_text = "batch has {} but master cost has {}".format(
961                            repr(row.case_quantity), repr(cost.case_size))
962                    elif batch.order_quantities_known and (
963                            self.get_units_ordered(row) != self.get_units_accounted_for(row)):
964                        row.status_code = row.STATUS_ORDERED_RECEIVED_DIFFER
965                    # TODO: is this right? should out of stock just be a filter for
966                    # the user to specify, or should it affect status?
967                    elif row.out_of_stock:
968                        row.status_code = row.STATUS_OUT_OF_STOCK
969                    else:
970                        row.status_code = row.STATUS_OK
971
972        else:
973            raise NotImplementedError("can't refresh row for batch of mode: {}".format(
974                self.enum.PURHASE_BATCH_MODE.get(batch.mode, "unknown ({})".format(batch.mode))))
975
976    def remove_row(self, row):
977        """
978        When removing a row from purchase batch, (maybe) must also update some
979        totals for the batch.
980        """
981        batch = row.batch
982
983        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
984            if row.po_total:
985                batch.po_total -= row.po_total
986
987        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
988            if row.invoice_total:
989                batch.invoice_total -= row.invoice_total
990
991        super(PurchaseBatchHandler, self).remove_row(row)
992
993    def refresh_totals(self, row, cost, initial):
994        batch = row.batch
995
996        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
997            if row.po_unit_cost:
998                row.po_total = row.po_unit_cost * self.get_units_ordered(row)
999                batch.po_total = (batch.po_total or 0) + row.po_total
1000            else:
1001                row.po_total = None
1002
1003        elif batch.mode in (self.enum.PURCHASE_BATCH_MODE_RECEIVING,
1004                            self.enum.PURCHASE_BATCH_MODE_COSTING):
1005            if row.invoice_unit_cost:
1006                row.invoice_total = row.invoice_unit_cost * self.get_units_accounted_for(row)
1007                batch.invoice_total = (batch.invoice_total or 0) + row.invoice_total
1008            else:
1009                row.invoice_total = None
1010
1011    def get_unit_cost(self, product, vendor):
1012        """
1013        Must return the PO unit cost for the given product, from the given vendor.
1014        """
1015        cost = product.cost_for_vendor(vendor) or product.cost
1016        if cost:
1017            return cost.unit_cost
1018
1019    def get_units(self, cases, units, case_quantity):
1020        case_quantity = case_quantity or 1
1021        return (units or 0) + case_quantity * (cases or 0)
1022
1023    def get_units_ordered(self, row, case_quantity=None):
1024        case_quantity = case_quantity or row.case_quantity or 1
1025        return self.get_units(row.cases_ordered, row.units_ordered, case_quantity)
1026
1027    # TODO: we now have shipped quantities...should return sum of those instead?
1028    def get_units_shipped(self, row, case_quantity=None):
1029        case_quantity = case_quantity or row.case_quantity or 1
1030        units_damaged = (row.units_damaged or 0) + case_quantity * (row.cases_damaged or 0)
1031        units_expired = (row.units_expired or 0) + case_quantity * (row.cases_expired or 0)
1032        return self.get_units_received(row) + units_damaged + units_expired
1033
1034    def get_units_received(self, row, case_quantity=None):
1035        case_quantity = case_quantity or row.case_quantity or 1
1036        return self.get_units(row.cases_received, row.units_received, case_quantity)
1037
1038    def get_units_damaged(self, row, case_quantity=None):
1039        case_quantity = case_quantity or row.case_quantity or 1
1040        return self.get_units(row.cases_damaged, row.units_damaged, case_quantity)
1041
1042    def get_units_expired(self, row, case_quantity=None):
1043        case_quantity = case_quantity or row.case_quantity or 1
1044        return self.get_units(row.cases_expired, row.units_expired, case_quantity)
1045
1046    def get_units_confirmed(self, row, case_quantity=None):
1047        received = self.get_units_received(row, case_quantity=case_quantity)
1048        damaged = self.get_units_damaged(row, case_quantity=case_quantity)
1049        expired = self.get_units_expired(row, case_quantity=case_quantity)
1050        return received + damaged + expired
1051
1052    def get_units_mispick(self, row, case_quantity=None):
1053        case_quantity = case_quantity or row.case_quantity or 1
1054        return self.get_units(row.cases_mispick, row.units_mispick, case_quantity)
1055
1056    def get_units_accounted_for(self, row, case_quantity=None):
1057        confirmed = self.get_units_confirmed(row, case_quantity=case_quantity)
1058        mispick = self.get_units_mispick(row, case_quantity=case_quantity)
1059        return confirmed + mispick
1060
1061    def get_units_shorted(self, obj, case_quantity=None):
1062        case_quantity = case_quantity or obj.case_quantity or 1
1063        if hasattr(obj, 'cases_shorted'):
1064            # obj is really a credit
1065            return self.get_units(obj.cases_shorted, obj.units_shorted, case_quantity)
1066        else:
1067            # obj is a row, so sum the credits
1068            return sum([self.get_units(credit.cases_shorted, credit.units_shorted, case_quantity)
1069                        for credit in obj.credits])
1070
1071    def get_units_claimed(self, row, case_quantity=None):
1072        """
1073        Returns the total number of units which are "claimed" by child rows,
1074        for the given truck dump parent row.
1075        """
1076        claimed = 0
1077        for claim in row.claims:
1078            # prefer child row's notion of case quantity, over parent row
1079            case_qty = case_quantity or claim.claiming_row.case_quantity or row.case_quantity
1080            claimed += self.get_units_confirmed(claim, case_quantity=case_qty)
1081        return claimed
1082
1083    def get_units_claimed_received(self, row, case_quantity=None):
1084        return sum([self.get_units_received(claim, case_quantity=row.case_quantity)
1085                    for claim in row.claims])
1086
1087    def get_units_claimed_damaged(self, row, case_quantity=None):
1088        return sum([self.get_units_damaged(claim, case_quantity=row.case_quantity)
1089                    for claim in row.claims])
1090
1091    def get_units_claimed_expired(self, row, case_quantity=None):
1092        return sum([self.get_units_expired(claim, case_quantity=row.case_quantity)
1093                    for claim in row.claims])
1094
1095    def get_units_available(self, row, case_quantity=None):
1096        confirmed = self.get_units_confirmed(row, case_quantity=case_quantity)
1097        claimed = self.get_units_claimed(row, case_quantity=case_quantity)
1098        return confirmed - claimed
1099
1100    def auto_receive_all_items(self, batch, progress=None):
1101        """
1102        Automatically "receive" all items for the given batch.  Meant for
1103        development purposes only!
1104        """
1105        if self.config.production():
1106            raise NotImplementedError("Feature is not meant for production use.")
1107
1108        def receive(row, i):
1109
1110            # auto-receive remaining cases
1111            cases_ordered = row.cases_ordered or 0
1112            cases_confirmed = ((row.cases_received or 0)
1113                               + (row.cases_damaged or 0)
1114                               + (row.cases_expired or 0))
1115            if cases_ordered > cases_confirmed:
1116                row.cases_received = (row.cases_received or 0) + (
1117                    cases_ordered - cases_confirmed)
1118
1119            # auto-receive remaining units
1120            units_ordered = row.units_ordered or 0
1121            units_confirmed = ((row.units_received or 0)
1122                               + (row.units_damaged or 0)
1123                               + (row.units_expired or 0))
1124            if units_ordered > units_confirmed:
1125                row.units_received = (row.units_received or 0) + (
1126                    units_ordered - units_confirmed)
1127
1128            # establish truck dump claims if applicable
1129            if (batch.is_truck_dump_parent()
1130                and batch.truck_dump_children_first
1131                and row.product):
1132                self.make_truck_dump_claims_for_parent_row(row)
1133
1134        self.progress_loop(receive, batch.active_rows(), progress,
1135                           message="Auto-receiving all items")
1136
1137    def update_order_counts(self, purchase, progress=None):
1138
1139        def update(item, i):
1140            if item.product:
1141                inventory = item.product.inventory or model.ProductInventory(product=item.product)
1142                inventory.on_order = (inventory.on_order or 0) + (item.units_ordered or 0) + (
1143                    (item.cases_ordered or 0) * (item.case_quantity or 1))
1144
1145        self.progress_loop(update, purchase.items, progress,
1146                           message="Updating inventory counts")
1147
1148    def update_receiving_inventory(self, purchase, consume_on_order=True, progress=None):
1149
1150        def update(item, i):
1151            if item.product:
1152                inventory = item.product.inventory or model.ProductInventory(product=item.product)
1153                count = (item.units_received or 0) + (item.cases_received or 0) * (item.case_quantity or 1)
1154                if count:
1155                    if consume_on_order:
1156                        if (inventory.on_order or 0) < count:
1157                            raise RuntimeError("Received {} units for {} but it only had {} on order".format(
1158                                count, item.product, inventory.on_order or 0))
1159                        inventory.on_order -= count
1160                    inventory.on_hand = (inventory.on_hand or 0) + count
1161
1162        self.progress_loop(update, purchase.items, progress,
1163                           message="Updating inventory counts")
1164
1165    def why_not_execute(self, batch):
1166        """
1167        This method should return a string indicating the reason why the given
1168        batch should not be considered executable.  By default it returns
1169        ``None`` which means the batch *is* to be considered executable.
1170
1171        Note that it is assumed the batch has not already been executed, since
1172        execution is globally prevented for such batches.
1173        """
1174        # not all receiving batches are executable
1175        if batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1176
1177            if batch.is_truck_dump_parent() and batch.status_code != batch.STATUS_TRUCKDUMP_CLAIMED:
1178                return ("Can't execute a Truck Dump (parent) batch until "
1179                        "it has been fully claimed by children")
1180
1181            if batch.is_truck_dump_child():
1182                return ("Can't directly execute batch which is child of a truck dump "
1183                        "(must execute truck dump instead)")
1184
1185    def execute(self, batch, user, progress=None):
1186        """
1187        Default behavior for executing a purchase batch will create a new
1188        purchase, by invoking :meth:`make_purchase()`.
1189        """
1190        session = orm.object_session(batch)
1191
1192        if batch.mode == self.enum.PURCHASE_BATCH_MODE_ORDERING:
1193            purchase = self.make_purchase(batch, user, progress=progress)
1194            self.update_order_counts(purchase, progress=progress)
1195            return purchase
1196
1197        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_RECEIVING:
1198            if self.allow_truck_dump and batch.is_truck_dump_parent():
1199                self.execute_truck_dump(batch, user, progress=progress)
1200                return True
1201            else:
1202                with session.no_autoflush:
1203                    return self.receive_purchase(batch, progress=progress)
1204
1205        elif batch.mode == self.enum.PURCHASE_BATCH_MODE_COSTING:
1206            # TODO: finish this...
1207            # with session.no_autoflush:
1208            #     return self.cost_purchase(batch, progress=progress)
1209            purchase = batch.purchase
1210            purchase.invoice_date = batch.invoice_date
1211            purchase.status = self.enum.PURCHASE_STATUS_COSTED
1212            return purchase
1213
1214        assert False
1215
1216    def execute_truck_dump(self, batch, user, progress=None):
1217        now = make_utc()
1218        for child in batch.truck_dump_children:
1219            if not self.execute(child, user, progress=progress):
1220                raise RuntimeError("Failed to execute child batch: {}".format(child))
1221            child.executed = now
1222            child.executed_by = user
1223
1224    def make_credits(self, batch, progress=None):
1225        session = orm.object_session(batch)
1226        mapper = orm.class_mapper(model.PurchaseBatchCredit)
1227
1228        def copy(row, i):
1229            for batch_credit in row.credits:
1230                credit = model.PurchaseCredit()
1231                for prop in mapper.iterate_properties:
1232                    if isinstance(prop, orm.ColumnProperty) and hasattr(credit, prop.key):
1233                        setattr(credit, prop.key, getattr(batch_credit, prop.key))
1234                credit.status = self.enum.PURCHASE_CREDIT_STATUS_NEW
1235                session.add(credit)
1236
1237        return self.progress_loop(copy, batch.active_rows(), progress,
1238                                  message="Creating purchase credits")
1239
1240    def make_purchase(self, batch, user, progress=None):
1241        """
1242        Effectively clones the given batch, creating a new Purchase in the
1243        Rattail system.
1244        """
1245        session = orm.object_session(batch)
1246        purchase = model.Purchase()
1247
1248        # TODO: should be smarter and only copy certain fields here
1249        skip_fields = [
1250            'date_received',
1251        ]
1252        for prop in orm.object_mapper(batch).iterate_properties:
1253            if prop.key in skip_fields:
1254                continue
1255            if hasattr(purchase, prop.key):
1256                setattr(purchase, prop.key, getattr(batch, prop.key))
1257
1258        def clone(row, i):
1259            item = model.PurchaseItem()
1260            # TODO: should be smarter and only copy certain fields here
1261            for prop in orm.object_mapper(row).iterate_properties:
1262                if hasattr(item, prop.key):
1263                    setattr(item, prop.key, getattr(row, prop.key))
1264            purchase.items.append(item)
1265
1266        with session.no_autoflush:
1267            self.progress_loop(clone, batch.active_rows(), progress,
1268                               message="Creating purchase items")
1269
1270        purchase.created = make_utc()
1271        purchase.created_by = user
1272        purchase.status = self.enum.PURCHASE_STATUS_ORDERED
1273        session.add(purchase)
1274        batch.purchase = purchase
1275        return purchase
1276
1277    def receive_purchase(self, batch, progress=None):
1278        """
1279        Update the purchase for the given batch, to indicate received status.
1280        """
1281        session = orm.object_session(batch)
1282        purchase = batch.purchase
1283        if not purchase:
1284            batch.purchase = purchase = model.Purchase()
1285
1286            # TODO: should be smarter and only copy certain fields here
1287            skip_fields = [
1288                'uuid',
1289                'date_received',
1290            ]
1291            with session.no_autoflush:
1292                for prop in orm.object_mapper(batch).iterate_properties:
1293                    if prop.key in skip_fields:
1294                        continue
1295                    if hasattr(purchase, prop.key):
1296                        setattr(purchase, prop.key, getattr(batch, prop.key))
1297
1298        purchase.invoice_number = batch.invoice_number
1299        purchase.invoice_date = batch.invoice_date
1300        purchase.invoice_total = batch.invoice_total
1301        purchase.date_received = batch.date_received
1302
1303        # determine which fields we'll copy when creating new purchase item
1304        copy_fields = []
1305        for prop in orm.class_mapper(model.PurchaseItem).iterate_properties:
1306            if hasattr(model.PurchaseBatchRow, prop.key):
1307                copy_fields.append(prop.key)
1308
1309        def update(row, i):
1310            item = row.item
1311            if not item:
1312                row.item = item = model.PurchaseItem()
1313                for field in copy_fields:
1314                    setattr(item, field, getattr(row, field))
1315                purchase.items.append(item)
1316
1317            item.cases_received = row.cases_received
1318            item.units_received = row.units_received
1319            item.cases_damaged = row.cases_damaged
1320            item.units_damaged = row.units_damaged
1321            item.cases_expired = row.cases_expired
1322            item.units_expired = row.units_expired
1323            item.invoice_line_number = row.invoice_line_number
1324            item.invoice_case_cost = row.invoice_case_cost
1325            item.invoice_unit_cost = row.invoice_unit_cost
1326            item.invoice_total = row.invoice_total
1327
1328        with session.no_autoflush:
1329            self.progress_loop(update, batch.active_rows(), progress,
1330                               message="Updating purchase line items")
1331
1332        purchase.status = self.enum.PURCHASE_STATUS_RECEIVED
1333        return purchase
1334
1335    def clone_row(self, oldrow):
1336        newrow = super(PurchaseBatchHandler, self).clone_row(oldrow)
1337
1338        for oldcredit in oldrow.credits:
1339            newcredit = model.PurchaseBatchCredit()
1340            self.copy_credit_attributes(oldcredit, newcredit)
1341            newrow.credits.append(newcredit)
1342
1343        return newrow
1344
1345    def copy_credit_attributes(self, source_credit, target_credit):
1346        mapper = orm.class_mapper(model.PurchaseBatchCredit)
1347        for prop in mapper.iterate_properties:
1348            if prop.key not in ('uuid', 'row_uuid'):
1349                if isinstance(prop, orm.ColumnProperty):
1350                    setattr(target_credit, prop.key, getattr(source_credit, prop.key))
Note: See TracBrowser for help on using the repository browser.