Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into uk/trial-length
Browse files Browse the repository at this point in the history
Conflicts:
	config/locales/en.yml
  • Loading branch information
mkllnk committed Jul 20, 2016
2 parents e252414 + ddb54d1 commit 984641e
Show file tree
Hide file tree
Showing 32 changed files with 320 additions and 149 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ angular.module("admin.indexUtils").directive "objForUpdate", (switchClass, pendi
scope.savedValue = value

scope.success = ->
switchClass( element, "update-success", ["update-pending", "update-error"], 3000 )
switchClass( element, "update-success", ["update-pending", "update-error"], 5000 )

scope.pending = ->
switchClass( element, "update-pending", ["update-error", "update-success"], false )
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Darkswarm.controller "GroupsCtrl", ($scope, Groups) ->
Darkswarm.controller "GroupsCtrl", ($scope, Groups, Search) ->
$scope.Groups = Groups
$scope.order = 'position'
$scope.query = Search.search()

$scope.$watch "query", (query)->
Search.search query
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
Darkswarm.directive "enterpriseModal", ($modal)->
Darkswarm.directive "enterpriseModal", ($modal, Enterprises, EnterpriseResource) ->
restrict: 'E'
replace: true
template: "<a ng-transclude></a>"
transclude: true
link: (scope, elem, attrs, ctrl)->
elem.on "click", (ev)=>
link: (scope, elem, attrs, ctrl) ->
elem.on "click", (ev) =>
ev.stopPropagation()
params =
id: scope.enterprise.id
EnterpriseResource.relatives params, (data) =>
Enterprises.addEnterprises data
scope.enterprise = Enterprises.enterprises_by_id[scope.enterprise.id]
Enterprises.dereferenceEnterprise scope.enterprise
scope.modalInstance = $modal.open(controller: ctrl, templateUrl: 'enterprise_modal.html', scope: scope)
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Darkswarm.directive 'mapOsmTiles', ($timeout) ->
restrict: 'E'
require: '^googleMap'
scope: {}
link: (scope, elem, attrs, ctrl) ->
$timeout =>
map = ctrl.getMap()

map.mapTypes.set 'OSM', new google.maps.ImageMapType
getTileUrl: (coord, zoom) ->
# "Wrap" x (logitude) at 180th meridian properly
# NB: Don't touch coord.x because coord param is by reference, and changing its x property breaks something in Google's lib
tilesPerGlobe = 1 << zoom
x = coord.x % tilesPerGlobe
if x < 0
x = tilesPerGlobe + x
# Wrap y (latitude) in a like manner if you want to enable vertical infinite scroll
'http://tile.openstreetmap.org/' + zoom + '/' + x + '/' + coord.y + '.png'
tileSize: new google.maps.Size(256, 256)
name: 'OpenStreetMap'
maxZoom: 18
82 changes: 45 additions & 37 deletions app/assets/javascripts/darkswarm/directives/map_search.js.coffee
Original file line number Diff line number Diff line change
@@ -1,46 +1,54 @@
Darkswarm.directive 'mapSearch', ($timeout)->
Darkswarm.directive 'mapSearch', ($timeout, Search) ->
# Install a basic search field in a map
restrict: 'E'
require: '^googleMap'
require: ['^googleMap', 'ngModel']
replace: true
template: '<input id="pac-input" placeholder="' + t('location_placeholder') + '"></input>'
link: (scope, elem, attrs, ctrl)->
template: '<input id="pac-input" ng-model="query" placeholder="' + t('location_placeholder') + '"></input>'
scope: {}

controller: ($scope) ->
$scope.query = Search.search()

$scope.$watch 'query', (query) ->
Search.search query


link: (scope, elem, attrs, ctrls) ->
[ctrl, model] = ctrls
scope.input = document.getElementById("pac-input")

$timeout =>
map = ctrl.getMap()

# Use OSM tiles server
map.mapTypes.set 'OSM', new (google.maps.ImageMapType)(
getTileUrl: (coord, zoom) ->
# "Wrap" x (logitude) at 180th meridian properly
# NB: Don't touch coord.x because coord param is by reference, and changing its x property breakes something in Google's lib
tilesPerGlobe = 1 << zoom
x = coord.x % tilesPerGlobe
if x < 0
x = tilesPerGlobe + x
# Wrap y (latitude) in a like manner if you want to enable vertical infinite scroll
'http://tile.openstreetmap.org/' + zoom + '/' + x + '/' + coord.y + '.png'
tileSize: new (google.maps.Size)(256, 256)
name: 'OpenStreetMap'
maxZoom: 18)

input = (document.getElementById("pac-input"))
map.controls[google.maps.ControlPosition.TOP_LEFT].push input
searchBox = new google.maps.places.SearchBox((input))

google.maps.event.addListener searchBox, "places_changed", ->
places = searchBox.getPlaces()
return if places.length is 0
# For each place, get the icon, place name, and location.
markers = []
bounds = new google.maps.LatLngBounds()
for place in places
#map.setCenter place.geometry.location
map.fitBounds place.geometry.viewport
#map.fitBounds bounds

# Bias the SearchBox results towards places that are within the bounds of the
# current map's viewport.
searchBox = scope.createSearchBox map
scope.bindSearchResponse map, searchBox
scope.biasResults map, searchBox
scope.performUrlSearch map

scope.createSearchBox = (map) ->
map.controls[google.maps.ControlPosition.TOP_LEFT].push scope.input
return new google.maps.places.SearchBox(scope.input)

scope.bindSearchResponse = (map, searchBox) ->
google.maps.event.addListener searchBox, "places_changed", =>
scope.showSearchResult map, searchBox

scope.showSearchResult = (map, searchBox) ->
places = searchBox.getPlaces()
for place in places when place.geometry.viewport?
map.fitBounds place.geometry.viewport
scope.$apply ->
model.$setViewValue elem.val()

# When the map loads, and we have a search from ?query, perform that search
scope.performUrlSearch = (map) ->
google.maps.event.addListenerOnce map, "idle", =>
google.maps.event.trigger(scope.input, 'focus');
google.maps.event.trigger(scope.input, 'keydown', {keyCode: 13});

# Bias the SearchBox results towards places that are within the bounds of the
# current map's viewport.
scope.biasResults = (map, searchBox) ->
google.maps.event.addListener map, "bounds_changed", ->
bounds = map.getBounds()
searchBox.setBounds bounds

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Darkswarm.filter 'products', (Matcher)->
(products, text)->
Darkswarm.filter 'products', (Matcher) ->
(products, text) ->
products ||= []
text ?= ""
products.filter (product)=>
products.filter (product) =>
propertiesToMatch = [product.name, product.supplier.name, product.primary_taxon.name]
Matcher.match propertiesToMatch, text
19 changes: 15 additions & 4 deletions app/assets/javascripts/darkswarm/services/dereferencer.js.coffee
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
Darkswarm.factory 'Dereferencer', ->
new class Dereferencer
dereference: (array, data)->
if array
for object, i in array
array[i] = data[object.id]
dereference: (array, data) ->
@dereference_from(array, array, data)

dereference_from: (source, target, data) ->
unreferenced = []
if source && target
for object, i in source
# skip empty entries in sparse array
continue unless source.hasOwnProperty(i)
key = object?.id
if data.hasOwnProperty(key)
target[i] = data[key]
else
unreferenced[i] = object
unreferenced
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Darkswarm.factory 'EnterpriseResource', ($resource) ->
$resource('/enterprise/:id.json', {}, {
'relatives':
method: 'GET'
url: '/enterprises/:id/relatives.json'
isArray: true
cache: true
})
29 changes: 21 additions & 8 deletions app/assets/javascripts/darkswarm/services/enterprises.js.coffee
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Darkswarm.factory 'Enterprises', (enterprises, CurrentHub, Taxons, Dereferencer, visibleFilter, Matcher, Geo, $rootScope)->
Darkswarm.factory 'Enterprises', (enterprises, CurrentHub, Taxons, Dereferencer, visibleFilter, Matcher, Geo, $rootScope) ->
new class Enterprises
enterprises_by_id: {}
constructor: ->
Expand All @@ -9,7 +9,6 @@ Darkswarm.factory 'Enterprises', (enterprises, CurrentHub, Taxons, Dereferencer,
@enterprises_by_id[enterprise.id] = enterprise
# Replace enterprise and taxons ids with actual objects.
@dereferenceEnterprises()
@dereferenceTaxons()
@visible_enterprises = visibleFilter @enterprises
@producers = @visible_enterprises.filter (enterprise)->
enterprise.category in ["producer_hub", "producer_shop", "producer"]
Expand All @@ -20,13 +19,27 @@ Darkswarm.factory 'Enterprises', (enterprises, CurrentHub, Taxons, Dereferencer,
if CurrentHub.hub?.id
CurrentHub.hub = @enterprises_by_id[CurrentHub.hub.id]
for enterprise in @enterprises
Dereferencer.dereference enterprise.hubs, @enterprises_by_id
Dereferencer.dereference enterprise.producers, @enterprises_by_id
@dereferenceEnterprise enterprise

dereferenceTaxons: ->
for enterprise in @enterprises
Dereferencer.dereference enterprise.taxons, Taxons.taxons_by_id
Dereferencer.dereference enterprise.supplied_taxons, Taxons.taxons_by_id
dereferenceEnterprise: (enterprise) ->
@dereferenceProperty(enterprise, 'hubs', @enterprises_by_id)
@dereferenceProperty(enterprise, 'producers', @enterprises_by_id)
@dereferenceProperty(enterprise, 'taxons', Taxons.taxons_by_id)
@dereferenceProperty(enterprise, 'supplied_taxons', Taxons.taxons_by_id)

dereferenceProperty: (enterprise, property, data) ->
# keep unreferenced enterprise ids
# in case we dereference again after adding more enterprises
enterprise.unreferenced |= {}
collection = enterprise[property]
unreferenced = enterprise.unreferenced[property] || collection
enterprise.unreferenced[property] =
Dereferencer.dereference_from unreferenced, collection, data

addEnterprises: (new_enterprises) ->
return unless new_enterprises && new_enterprises.length
for enterprise in new_enterprises
@enterprises_by_id[enterprise.id] = enterprise

flagMatching: (query) ->
for enterprise in @enterprises
Expand Down
16 changes: 14 additions & 2 deletions app/controllers/enterprises_controller.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'open_food_network/enterprise_injection_data'

class EnterprisesController < BaseController
layout "darkswarm"
helper Spree::ProductsHelper
Expand All @@ -11,19 +13,29 @@ class EnterprisesController < BaseController

respond_to :js, only: :permalink_checker

def relatives
respond_to do |format|
format.json do
enterprise = Enterprise.find(params[:id])
enterprises = enterprise.andand.relatives.andand.activated
render(json: enterprises,
each_serializer: Api::EnterpriseSerializer,
data: OpenFoodNetwork::EnterpriseInjectionData.new)
end
end
end

def check_permalink
return render text: params[:permalink], status: 409 if Enterprise.find_by_permalink params[:permalink]

path = Rails.application.routes.recognize_path( "/#{ params[:permalink].to_s }" )
path = Rails.application.routes.recognize_path("/#{params[:permalink].to_s}")
if path && path[:controller] == "cms_content"
render text: params[:permalink], status: 200
else
render text: params[:permalink], status: 409
end
end


private

def clean_permalink
Expand Down
1 change: 1 addition & 0 deletions app/helpers/checkout_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def checkout_adjustments_for(order, opts={})
# Remove empty tax adjustments and (optionally) shipping fees
adjustments.reject! { |a| a.originator_type == 'Spree::TaxRate' && a.amount == 0 }
adjustments.reject! { |a| a.originator_type == 'Spree::ShippingMethod' } if exclude.include? :shipping
adjustments.reject! { |a| a.originator_type == 'Spree::PaymentMethod' } if exclude.include? :payment
adjustments.reject! { |a| a.source_type == 'Spree::LineItem' } if exclude.include? :line_item

enterprise_fee_adjustments = adjustments.select { |a| a.originator_type == 'EnterpriseFee' && a.source_type != 'Spree::LineItem' }
Expand Down
13 changes: 13 additions & 0 deletions app/helpers/injection_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ def inject_enterprises
inject_json_ams "enterprises", Enterprise.activated.includes(address: :state).all, Api::EnterpriseSerializer, enterprise_injection_data
end

def inject_enterprise_and_relatives
inject_json_ams "enterprises", current_distributor.relatives_including_self.activated.includes(address: :state).all, Api::EnterpriseSerializer, enterprise_injection_data
end

def inject_shop_enterprises
ocs = if current_order_cycle
[current_order_cycle]
else
OrderCycle.not_closed.with_distributor(current_distributor)
end
inject_json_ams "enterprises", current_distributor.plus_relatives_and_oc_producers(ocs).activated.includes(address: :state).all, Api::EnterpriseSerializer, enterprise_injection_data
end

def inject_group_enterprises
inject_json_ams "group_enterprises", @group.enterprises.activated.all, Api::EnterpriseSerializer, enterprise_injection_data
end
Expand Down
15 changes: 15 additions & 0 deletions app/models/enterprise.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,16 @@ class Enterprise < ActiveRecord::Base
joins(:enterprise_roles).where('enterprise_roles.user_id = ?', user.id)
end
}
scope :relatives_of_one_union_others, lambda { |one, others|
where("
enterprises.id IN
(SELECT child_id FROM enterprise_relationships WHERE enterprise_relationships.parent_id=?)
OR enterprises.id IN
(SELECT parent_id FROM enterprise_relationships WHERE enterprise_relationships.child_id=?)
OR enterprises.id IN
(?)
", one, one, others)
}

# Force a distinct count to work around relation count issue https://github.com/rails/rails/issues/5554
def self.distinct_count
Expand Down Expand Up @@ -220,6 +230,11 @@ def relatives
", self.id, self.id)
end

def plus_relatives_and_oc_producers(order_cycles)
oc_producer_ids = Exchange.in_order_cycle(order_cycles).incoming.pluck :sender_id
Enterprise.relatives_of_one_union_others(id, oc_producer_ids | [id])
end

def relatives_including_self
Enterprise.where(id: relatives.pluck(:id) | [id])
end
Expand Down
7 changes: 6 additions & 1 deletion app/models/spree/payment_decorator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ module Spree
after_save :ensure_correct_adjustment, :update_order

def ensure_correct_adjustment
if adjustment
# Don't charge for invalid payments.
# PayPalExpress always creates a payment that is invalidated later.
# Unknown: What about failed payments?
if state == "invalid"
adjustment.andand.destroy
elsif adjustment
adjustment.originator = payment_method
adjustment.label = adjustment_label
adjustment.save
Expand Down
2 changes: 1 addition & 1 deletion app/views/checkout/_summary.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
= t :checkout_cart_total
%td.cart-total.text-right= display_checkout_subtotal(@order)

- checkout_adjustments_for(current_order, exclude: [:shipping, :line_item]).reject{ |a| a.amount == 0 }.each do |adjustment|
- checkout_adjustments_for(current_order, exclude: [:shipping, :payment, :line_item]).reject{ |a| a.amount == 0 }.each do |adjustment|
%tr
%th= adjustment.label
%td.text-right= adjustment.display_amount.to_html
Expand Down
2 changes: 1 addition & 1 deletion app/views/checkout/edit.html.haml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
- content_for(:title) do
= t :checkout_title

= inject_enterprises
= inject_enterprise_and_relatives

.darkswarm.footer-pad
- content_for :order_cycle_form do
Expand Down
2 changes: 1 addition & 1 deletion app/views/enterprises/shop.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
- content_for(:image) do
= current_distributor.logo.url

= inject_enterprises
= inject_shop_enterprises

%shop.darkswarm
- content_for :order_cycle_form do
Expand Down
1 change: 1 addition & 0 deletions app/views/groups/show.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
.map-container
%map{"ng-if" => "(isActive(\'/map\') && (mapShowed = true)) || mapShowed"}
%google-map{options: "map.additional_options", center: "map.center", zoom: "map.zoom", styles: "map.styles", draggable: "true"}
%map-osm-tiles
%map-search
%markers{models: "mapMarkers", fit: "true",
coords: "'self'", icon: "'icon'", click: "'reveal'"}
Expand Down
1 change: 1 addition & 0 deletions app/views/map/index.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
.map-container{"fill-vertical" => true}
%map{"ng-controller" => "MapCtrl"}
%google-map{options: "map.additional_options", center: "map.center", zoom: "map.zoom", styles: "map.styles", draggable: "true"}
%map-osm-tiles
%map-search
%markers{models: "OfnMap.enterprises", fit: "true",
coords: "'self'", icon: "'icon'", click: "'reveal'"}
Expand Down
Loading

0 comments on commit 984641e

Please sign in to comment.