def test_till_open_previously_opened(self): yesterday = localnow() - datetime.timedelta(1) # Open a till, set the opening_date to yesterday till = Till(station=get_current_station(self.store), store=self.store) till.open_till() till.opening_date = yesterday till.add_credit_entry(currency(10), u"") till.close_till() till.closing_date = yesterday new_till = Till(station=get_current_station(self.store), store=self.store) self.failUnless(new_till._get_last_closed_till()) new_till.open_till() self.assertEquals(new_till.initial_cash_amount, till.final_cash_amount)
def _update_te(self): user = get_current_user(self.store) station = get_current_station(self.store) self.te_modified.te_time = TransactionTimestamp() self.te_modified.user_id = user and user.id self.te_modified.station_id = station and station.id
def _get_interface(cls, iface): store = get_default_store() station = get_current_station(store) device = DeviceSettings.get_by_station_and_type(store, station, iface) if not device: return None return device.get_interface()
def before_start(self, store): till = Till.get_current(store) if till is None: till = Till(store=store, station=get_current_station(store)) till.open_till() assert till == Till.get_current(store)
def test_till_open_previously_opened(self): yesterday = localnow() - datetime.timedelta(1) # Open a till, set the opening_date to yesterday till = Till(station=get_current_station(self.store), store=self.store) till.open_till() till.opening_date = yesterday till.add_credit_entry(currency(10), u"") till.close_till() till.closing_date = yesterday new_till = Till(station=get_current_station(self.store), store=self.store) self.assertTrue(new_till._get_last_closed_till()) new_till.open_till() self.assertEqual(new_till.initial_cash_amount, till.final_cash_amount)
def _check_branch(self): from stoqlib.database.runtime import (get_default_store, new_store, get_current_station, set_current_branch_station) from stoqlib.domain.person import Company from stoqlib.lib.parameters import sysparam from stoqlib.lib.message import info default_store = get_default_store() compaines = default_store.find(Company) if (compaines.count() == 0 or not sysparam.has_object('MAIN_COMPANY')): from stoqlib.gui.base.dialogs import run_dialog from stoqlib.gui.dialogs.branchdialog import BranchDialog if self._ran_wizard: info(_("You need to register a company before start using Stoq")) else: info(_("Could not find a company. You'll need to register one " "before start using Stoq")) store = new_store() person = run_dialog(BranchDialog, None, store) if not person: raise SystemExit branch = person.branch sysparam.set_object(store, 'MAIN_COMPANY', branch) current_station = get_current_station(store) if current_station is not None: current_station.branch = branch store.commit() store.close() set_current_branch_station(default_store, station_name=None)
def get_scale_settings(cls, store): """ Get the scale device settings for the current station :param store: a store :returns: a :class:`DeviceSettings` object or None if there is none """ station = get_current_station(store) return cls.get_by_station_and_type(store, station, cls.SCALE_DEVICE)
def testTillOpenOnce(self): station = get_current_station(self.store) till = Till(store=self.store, station=station) till.open_till() till.close_till() self.assertRaises(TillError, till.open_till)
def get_scale_settings(cls, store): """ Get the scale device settings for the current station :param store: a store :returns: a :class:`DeviceSettings` object or None if there is none """ station = get_current_station(store) return store.find(cls, station=station, type=cls.SCALE_DEVICE).one()
def can_activate_printer(self): serial = self.model.device_serial printers = self.store.find(ECFPrinter, is_active=True, station=get_current_station(self.store)) till = self.store.find(Till, status=Till.STATUS_OPEN, station=get_current_station(self.store)).one() if till and printers: warning(_("You need to close the till opened at %s before " "changing this printer.") % till.opening_date.date()) return False for p in printers: if p.device_serial != serial and self.model.is_active: warning(_(u'The ECF %s is already active for this ' 'station. Deactivate that printer before ' 'activating this one.') % p.model) return False return True
def _update_te(self): user = get_current_user(self.store) station = get_current_station(self.store) self.te.dirty = True self.te.te_time = StatementTimestamp() self.te.user_id = user and user.id self.te.station_id = station and station.id
def test_till_open_once(self): station = get_current_station(self.store) till = Till(store=self.store, station=station) till.open_till() till.close_till() self.assertRaises(TillError, till.open_till)
def test_till_open_other_station(self): till = Till(station=self.create_station(), store=self.store) till.open_till() till = Till(station=get_current_station(self.store), store=self.store) till.open_till() self.assertEqual(Till.get_last_opened(self.store), till)
def testGetCurrentTillClose(self): station = get_current_station(self.store) self.assertEqual(Till.get_current(self.store), None) till = Till(store=self.store, station=station) till.open_till() self.assertEqual(Till.get_current(self.store), till) till.close_till() self.assertEqual(Till.get_current(self.store), None)
def __init__(self, store, model=None, visual_mode=False): BaseEditor.__init__(self, store, model, visual_mode) # do not let the user change the current station if model and get_current_station(store) == model: self.name.set_sensitive(False) self.is_active.set_sensitive(False) self.set_description(self.model.name)
def testCreate(self, select): # Station names change depending on the computer running the test. Make # sure only one station is in the list, and that the name is always de # same station = get_current_station(self.store) station.name = u'Test station' select.return_value = [station] editor = InvoicePrinterEditor(self.store) self.check_editor(editor, 'editor-invoiceprinter-create')
def __init__(self, *args, **kwargs): if not kwargs.get('station_id', None) and not kwargs.get('station', None): # Use the station_id, since the object is not from the same store. kwargs['station_id'] = get_current_station().id if (not kwargs.get('branch_id', None) and not kwargs.get('branch', None) and type(self).__name__ != 'TransferOrder'): # Add a branch_id if None was provided kwargs['branch_id'] = get_current_branch().id super(IdentifiableDomain, self).__init__(*args, **kwargs)
def test_get_current_till_close(self): station = get_current_station(self.store) self.assertEqual(Till.get_current(self.store), None) till = Till(store=self.store, station=station) till.open_till() self.assertEqual(Till.get_current(self.store), till) till.close_till() self.assertEqual(Till.get_current(self.store), None)
def test_till_open_once(self): station = get_current_station(self.store) till = Till(store=self.store, station=station) till.open_till() till.close_till() with mock.patch.object(PluginManager, 'is_active') as is_active: is_active.return_value = True self.assertRaises(TillError, till.open_till)
def check_drawer(store=None): from .restful import DrawerResource try: return DrawerResource.ensure_printer(get_current_station(store), retries=1) except (SerialException, InvalidReplyException, PrinterError): return None except socket.timeout as error: logger.warning(error) return None
def test_till_history_report(self): from stoqlib.gui.dialogs.tillhistory import TillHistoryDialog dialog = TillHistoryDialog(self.store) till = Till(station=get_current_station(self.store), store=self.store) till.open_till() sale = self.create_sale() sellable = self.create_sellable() sale.add_sellable(sellable, price=100) method = PaymentMethod.get_by_name(self.store, u"bill") payment = method.create_payment(Payment.TYPE_IN, sale.group, sale.branch, Decimal(100)) TillEntry( value=25, identifier=20, description=u"Cash In", payment=None, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store, ) TillEntry( value=-5, identifier=21, description=u"Cash Out", payment=None, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store, ) TillEntry( value=100, identifier=22, description=sellable.get_description(), payment=payment, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store, ) till_entry = list(self.store.find(TillEntry, till=till)) today = datetime.date.today().strftime("%x") for item in till_entry: if today in item.description: date = datetime.date(2007, 1, 1).strftime("%x") item.description = item.description.replace(today, date) item.date = datetime.date(2007, 1, 1) dialog.results.append(item) self._diff_expected(TillHistoryReport, "till-history-report", dialog.results, list(dialog.results))
def test_till_open_previously_not_closed(self): yesterday = localnow() - datetime.timedelta(1) # Open a till, set the opening_date to yesterday till = Till(station=get_current_station(self.store), store=self.store) till.open_till() till.opening_date = yesterday till.close_till() till.closing_date = None self.assertRaises(TillError, till.open_till)
def run_flaskserver(port, debug=False, multiclient=False): from stoqlib.lib.environment import configure_locale # Force pt_BR for now. configure_locale('pt_BR') global is_multiclient is_multiclient = multiclient from .workers import WORKERS # For now we're disabling workers when stoqserver is serving multiple clients (multiclient mode) # FIXME: a proper solution would be to modify the workflow so that the clients ask the server # about devices health, the till status, etc. instead of the other way around. if not is_multiclient: for function in WORKERS: gevent.spawn(function, get_current_station(api.get_default_store())) try: from stoqserver.lib import stacktracer stacktracer.start_trace("/tmp/trace-stoqserver-flask.txt", interval=5, auto=True) except ImportError: pass app = bootstrap_app() app.debug = debug if not is_developer_mode(): sentry.raven_client = Sentry(app, dsn=SENTRY_URL, client=raven_client) @app.after_request def after_request(response): # Add all the CORS headers the POS needs to have its ajax requests # accepted by the browser origin = request.headers.get('origin') if not origin: origin = request.args.get('origin', request.form.get('origin', '*')) response.headers['Access-Control-Allow-Origin'] = origin response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE' response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type' response.headers['Access-Control-Allow-Credentials'] = 'true' return response from stoqserver.lib.restful import has_sat, has_nfe logger.info('Starting wsgi server (has_sat=%s, has_nfe=%s)', has_sat, has_nfe) http_server = WSGIServer(('0.0.0.0', port), app, spawn=gevent.spawn_raw, log=logger, error_log=logger) if debug: gevent.spawn(_gtk_main_loop) @run_with_reloader def run_server(): http_server.serve_forever() run_server() else: http_server.serve_forever()
def _on_object_added(self, obj_info): store = obj_info.get("store") store.block_implicit_flushes() user = get_current_user(store) station = get_current_station(store) store.unblock_implicit_flushes() self.te = TransactionEntry(store=store, te_time=StatementTimestamp(), user_id=user and user.id, station_id=station and station.id)
def __init__(self, *args, **kwargs): if not kwargs.get('station_id', None) and not kwargs.get( 'station', None): # Use the station_id, since the object is not from the same store. kwargs['station_id'] = get_current_station().id if (not kwargs.get('branch_id', None) and not kwargs.get('branch', None) and type(self).__name__ != 'TransferOrder'): # Add a branch_id if None was provided kwargs['branch_id'] = get_current_branch().id super(IdentifiableDomain, self).__init__(*args, **kwargs)
def _open_till(self, store, initial_cash_amount=0): station = get_current_station(store) last_till = Till.get_last(store) if not last_till or last_till.status != Till.STATUS_OPEN: # Create till and open till = Till(store=store, station=station) till.open_till() till.initial_cash_amount = decimal.Decimal(initial_cash_amount) else: # Error, till already opened assert False
def _logout(self): from stoqlib.database.runtime import (get_current_user, get_current_station, get_default_store) log.debug('Logging out the current user') try: store = get_default_store() user = get_current_user(store) if user: user.logout(get_current_station(store)) except StoqlibError: pass
def get_current_cheque_printer_settings(store): res = store.find(DeviceSettings, station=get_current_station(store), type=DeviceSettings.CHEQUE_PRINTER_DEVICE).one() if not res: return None elif not isinstance(res, DeviceSettings): raise TypeError("Invalid setting returned by " "get_current_cheque_printer_settings") return ChequePrinter(brand=res.brand, model=res.model, device=res.device_name)
def create_model(self, store): model = ECFPrinter(brand=u'daruma', model=u'FS345', device_name=u'/dev/ttyS0', device_serial=u'', baudrate=9600, station=get_current_station(store), is_active=True, store=store) if platform.system() == 'Windows': model.device_name = u'COM1' return model
def testTillOpenPreviouslyNotClosed(self): yesterday = datetime.datetime.today() - datetime.timedelta(1) # Open a till, set the opening_date to yesterday till = Till(station=get_current_station(self.store), store=self.store) till.open_till() till.opening_date = yesterday till.close_till() till.closing_date = None self.assertRaises(TillError, till.open_till)
def _on_object_added(self, obj_info): store = obj_info.get("store") store.block_implicit_flushes() user = get_current_user(store) station = get_current_station(store) store.unblock_implicit_flushes() self.te = TransactionEntry(store=store, te_time=StatementTimestamp(), user_id=user and user.id, station_id=station and station.id) store.add_created_object(self)
def test_get_current_till_open(self): self.assertEqual(Till.get_current(self.store), None) station = get_current_station(self.store) till = Till(store=self.store, station=station) self.assertEqual(Till.get_current(self.store), None) till.open_till() self.assertEqual(Till.get_current(self.store), till) self.assertEqual(till.opening_date.date(), localtoday().date()) self.assertEqual(till.status, Till.STATUS_OPEN) self.assertRaises(TillError, till.open_till)
def testGetCurrentTillOpen(self): self.assertEqual(Till.get_current(self.store), None) station = get_current_station(self.store) till = Till(store=self.store, station=station) self.assertEqual(Till.get_current(self.store), None) till.open_till() self.assertEqual(Till.get_current(self.store), till) self.assertEqual(till.opening_date.date(), localtoday().date()) self.assertEqual(till.status, Till.STATUS_OPEN) self.assertRaises(TillError, till.open_till)
def create_ecf_printer(self): printer = ECFPrinter( store=self.store, station=get_current_station(self.store), brand=u'virtual', model=u'Simple', device_name=u'', device_serial=u'', baudrate=9600, is_active=True, ) printer.create_fiscal_printer_constants() return printer
def get_last_opened(cls, store): """Fetches the last Till which was opened. If in doubt, use Till.get_current instead. This method is a special case which is used to be able to close a till without calling get_current() :param store: a store """ result = store.find(Till, status=Till.STATUS_OPEN, station=get_current_station(store)) result = result.order_by(Till.opening_date) if not result.is_empty(): return result[0]
def _create_printer(self): if self._printer: return self._printer station = get_current_station(self.default_store) printer = self.default_store.find(ECFPrinter, station=station, is_active=True).one() if not printer: return None try: self._printer = CouponPrinter(printer) except SerialException, e: warning(_('Error opening serial port'), str(e))
def create_model(self, store): model = ECFPrinter( brand=u"daruma", model=u"FS345", device_name=u"/dev/ttyS0", device_serial=u"", baudrate=9600, station=get_current_station(store), is_active=True, store=store, ) if platform.system() == "Windows": model.device_name = u"COM1" return model
def test_till_history_report(self): from stoqlib.gui.dialogs.tillhistory import TillHistoryDialog dialog = TillHistoryDialog(self.store) till = Till(station=get_current_station(self.store), store=self.store) till.open_till() sale = self.create_sale() sellable = self.create_sellable() sale.add_sellable(sellable, price=100) method = PaymentMethod.get_by_name(self.store, u'bill') payment = method.create_payment(Payment.TYPE_IN, sale.group, sale.branch, Decimal(100)) TillEntry(value=25, identifier=20, description=u"Cash In", payment=None, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store) TillEntry(value=-5, identifier=21, description=u"Cash Out", payment=None, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store) TillEntry(value=100, identifier=22, description=sellable.get_description(), payment=payment, till=till, branch=till.station.branch, date=datetime.date(2007, 1, 1), store=self.store) till_entry = list(self.store.find(TillEntry, till=till)) today = datetime.date.today().strftime('%x') for item in till_entry: if today in item.description: date = datetime.date(2007, 1, 1).strftime('%x') item.description = item.description.replace(today, date) item.date = datetime.date(2007, 1, 1) dialog.results.append(item) self._diff_expected(TillHistoryReport, 'till-history-report', dialog.results, list(dialog.results))
def ensure_printer(cls, retries=20): assert _printer_lock.locked() store = api.get_default_store() device = DeviceSettings.get_by_station_and_type(store, get_current_station(store), DeviceSettings.NON_FISCAL_PRINTER_DEVICE) if not device: # If we have no printer configured, there's nothing to ensure return # There is no need to lock the printer here, since it should already be locked by the # calling site of this method. # Test the printer to see if its working properly. printer = None try: printer = api.device_manager.printer return printer.is_drawer_open() except SerialException: if printer: printer._port.close() api.device_manager._printer = None for i in range(retries): log.info('Printer check failed. Reopening') try: printer = api.device_manager.printer printer.is_drawer_open() break except SerialException: gevent.sleep(1) else: # Reopening printer failed. re-raise the original exception raise # Invalidate the printer in the plugins so that it re-opens it manager = get_plugin_manager() sat = get_plugin(manager, 'sat') if sat and sat.ui: sat.ui.printer = None nfce = get_plugin(manager, 'nfce') if nfce and nfce.ui: nfce.ui._emitter.printer._driver = printer nonfiscal = get_plugin(manager, 'nonfiscal') if nonfiscal and nonfiscal.ui: nonfiscal.ui.printer = printer return printer.is_drawer_open()
def test_till_open_yesterday(self): yesterday = localnow() - datetime.timedelta(1) # Open a till, set the opening_date to yesterday till = Till(station=get_current_station(self.store), store=self.store) till.open_till() till.opening_date = yesterday self.assertRaises(TillError, Till.get_current, self.store) # This is used to close a till self.assertEqual(Till.get_last_opened(self.store), till) till.close_till() self.assertEqual(Till.get_current(self.store), None)
def get_current(cls, store): """Fetches the Till for the current station. :param store: a store :returns: a Till instance or None """ station = get_current_station(store) assert station is not None till = store.find(cls, status=Till.STATUS_OPEN, station=station).one() if till and till.needs_closing(): fmt = _("You need to close the till opened at %s before " "doing any fiscal operations") raise TillError(fmt % (till.opening_date.date(), )) return till
def _get_scale(store): """ Returns a Scale instance pre-configured for the current workstation. """ global _scale if _scale: return _scale settings = DeviceSettings.get_scale_settings(store) if settings and settings.is_active: _scale = Scale(brand=settings.brand, model=settings.model, device=settings.device_name) else: warning(_(u"There is no scale configured"), _(u"There is no scale configured for this station " "(\"%s\") or the scale is not enabled currently" % get_current_station(store).name)) return _scale
def create_ecf_printer(self): printer = ECFPrinter( store=self.store, station=get_current_station(self.store), brand=u'virtual', model=u'Simple', device_name=u'', device_serial=u'', baudrate=9600, is_active=True, ) # This might load state from disk that says that # the printer is closed, we don't care about that, # so override whatever state was loaded from disk so that # the tests can pass. printer.till_closed = False printer.create_fiscal_printer_constants() return printer